Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
A big reason why I use OOP is to create code that is easily reusable. For that purpose Java style interfaces are perfect. However, when dealing with C++ I really can't achieve any sort of functionality like interfaces... at least not with ease. I know about pure virtual base classes, but what really ticks me off is that they force me into really awkward code with pointers. E.g. `map<int, Node*> nodes;` (where Node is the virtual base class). This is sometimes ok, but sometimes pointers to base classes are just not a possible solution. E.g. if you want to return an object packaged as an interface you would have to return a base-class-casted pointer to the object.. but that object is on the stack and won't be there after the pointer is returned. Of course you could start using the heap extensively to avoid this but that's adding so much more work than there should be (avoiding memory leaks). Is there any way to achieve interface-like functionality in C++ without have to awkwardly deal with pointers and the heap?? (Honestly for all that trouble and awkardness id rather just stick with C.)
Template MetaProgramming is a pretty cool thing. The basic idea? "Compile time polymorphism and implicit interfaces", *Effective C++*. Basically you can get the interfaces you want via templated classes. A **VERY** simple example: ``` template <class T> bool foo( const T& _object ) { if ( _object != _someStupidObject && _object > 0 ) return true; return false; } ``` So in the above code what can we say about the object T? Well it must be compatible with '\_someStupidObject' OR it must be convertible to a type which is compatible. It must be comparable with an integral value, or again convertible to a type which is. So we have now defined an interface for the class T. The book "Effective C++" offers a much better and more detailed explanation. Hopefully the above code gives you some idea of the "interface" capability of templates. Also have a look at pretty much any of the boost libraries they are almost all chalk full of templatization.
You can use boost::shared\_ptr<T> to avoid the raw pointers. As a side note, the reason why you don't see a pointer in the Java syntax has nothing to do with how C++ implements interfaces vs. how Java implements interfaces, but rather it is the result of the fact that all objects in Java are implicit pointers (the \* is hidden).
Achieving Interface functionality in C++
[ "", "c++", "oop", "memory", "pointers", "interface", "" ]
Currently I am working on a piece of software, which is currently written 100% in Objective-C using the iPhone 3.0 SDK. I have come to a cross roads where I need to do quite a bit or string concatenation, more specifically, NSString concatenation and so far I have been doing it like this: **Objective-C string concatenation:** ``` NSString *resultantString = (NSMutableString*)[@"Hello " stringByAppendingString: @"World"]; ``` Now as you can imagine this gets quite difficult to read when I try to concatenate 6 NSStrings together. At first I contemplated mixing in an Objective-C++ class to do my string concatenation and hand it back to my Objective-C class as then I could use C++'s easy string concatenation like: **C++ string concatenation:** ``` string cppString = "Hello" + "World" + "see" + "easy!"; ``` I could use **C** char arrays but that would be a little more difficult to read. It then struck me that I could use a Python or Ruby bridge in Cocoa (which provide the added bonus of Regular expressions and superior string handling than the C based languages do). This made sense to me even though I have coded only small amounts of Ruby and Python, because they are billed as string manipulation languages. Perl I decided to skip because it isn't directly supported in Xcode. I am also interested in performance, so I am looking for the fastest way to do my string concatenation. So what should I do? Is there some deviously easy way I am missing in Objective-C to concatenate many strings at once say 10 strings? or is my idea to use Python or Ruby class methods that return a concatenated or regex modified strings not as incredibly insane as it sounds? Perhaps I even missed some another way to do this? **Update:** Yes. It seems I was rather crazy for thinking of pulling in another language runtime to do string manipulation, especially since I noted that I was concerned with speed. Adding a bridge would probably be much slower than simply using NSString/NSMutableString.
For fixed size concatenation, you can use `[NSString stringWithFormat:]` like: ``` NSString *str = [NSString stringWithFormat:@"%@ %@ %@", @"Hello", @"World", @"Yay!"]; ```
you can use join operation. ``` NSArray *chunks = ... get an array, say by splitting it; string = [chunks componentsJoinedByString: @" :-) "]; ``` would produce something like oop :-) ack :-) bork :-) greeble :-) ponies
Objective-C string manipulation
[ "", "python", "objective-c", "ruby", "string", "objective-c++", "" ]
I am starting to delve into the world of webOS and the Mojo SDK and having a great time so far, but I find myself having to constantly take a detour and read up on different subjects such as JSON, JavaScript, etc. I realize now that instead of diving in head first I probably should have done some reading on the core technologies behind webOS, and so I turn to the stackoverflow community for some advice. I am looking for some recommendations on reading material (or any resources, really) related to JavaScript, and webOS development in general. The Palm developer site hasn't been too wonderful thus far. I've messed with JavaScript a tiny bit, but am definitely still a beginner when it comes to that realm.
I have read some JavaScript books, and the book [Object-Oriented JavaScript](https://rads.stackoverflow.com/amzn/click/com/1847194141) is quite good. Despite the name, it goes into detail about basics too, so it is suitable to JavaScript beginners. However, it is a little lacking in not talking about the DOM much: You won't learn many tricks regarding working with HTML documents, but it's a good book to teach you JavaScript as a language and various useful techniques.
I picked up the following from O'Reilly: * [Palm WebOS](http://oreilly.com/catalog/9780596155261) * [Javascript - The Good Parts](http://oreilly.com/catalog/9780596517748/) Also, online you can check out: * <http://developer.palm.com/> * <http://www.webos-internals.org/wiki/Main_Page> * <http://www.precentral.net/> * <http://www.webosboston.org/> * <http://www.webos-internals.org/wiki/Resources>
Recommended reading material for getting started with webOS/Mojo SDK development?
[ "", "javascript", "json", "palm-pre", "mojo", "" ]
I have to execute long running threads in a WebLogic Bea 10.0 M1 server environment. I tried to use WorkManagers for this. Using an own WorkManager allows me to specify my own thread timeout (MaxThreadStuckTime) instead of adjusting the timeout for the whole business application. My setup is as follows: **weblogic-ejb-jar.xml:** ``` <?xml version="1.0" encoding="UTF-8"?> <weblogic-ejb-jar xmlns="http://www.bea.com/ns/weblogic/90" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.bea.com/ns/weblogic/90 http://www.bea.com/ns/weblogic/90/weblogic-ejb-jar.xsd"> <weblogic-enterprise-bean> <ejb-name>TestBean</ejb-name> <resource-description> <res-ref-name>myWorkManager</res-ref-name> <jndi-name>wm/myWorkManager</jndi-name> </resource-description> </weblogic-enterprise-bean> </weblogic-ejb-jar> ``` **weblogic-application.xml:** ``` <?xml version="1.0" encoding="UTF-8"?> <weblogic xmlns="http://www.bea.com/ns/weblogic/90" xmlns:j2ee="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.bea.com/ns/weblogic/90 http://www.bea.com/ns/weblogic/90/weblogic.xsd"> <work-manager> <name>myWorkManager</name> <ignore-stuck-threads>1</ignore-stuck-threads> </work-manager> </weblogic> ``` **and the Bean:** ``` import javax.annotation.Resource; import javax.ejb.Stateful; import weblogic.work.WorkManager; @Stateful(mappedName = "TestBean") public class TestBean implements TestBeanRemote { @Resource(name = "myWorkManager") private WorkManager myWorkManager; public void test() { myWorkManager.schedule(new Runnable() { public void run() { while (true) { System.out.println("test: +++++++++++++++++++++++++"); try { Thread.sleep(45000); } catch (InterruptedException e) { e.printStackTrace(); } } } }); } } ``` When I try to deploy this things, the server gives me the following exceptions: ``` [EJB:011026]The EJB container failed while creating the java:/comp/env namespace for this EJB deployment. weblogic.deployment.EnvironmentException: [EJB:010176]The resource-env-ref 'myWorkManager' declared in the ejb-jar.xml descriptor has no JNDI name mapped to it. The resource-ref must be mapped to a JNDI name using the resource-description element of the weblogic-ejb-jar.xml descriptor. ``` I try to figure out how to access / use WorkMangers for days now, and still get this or that as an exception. Very frustrating! Thanks in advance!
You need to remove the WorkManager refrence from your **weblogic-ejb-jar.xml**, this refenece should go to **ejb-jar.xml**. Infact I doubt if Weblogic schema definition "weblogic-ejb-jar.xsd" will allow you to add a reference element, you must be getting xsd validation errors. anyways, get rid of the element > ***resource-description*** from ***weblogic-ejb-jar.xml*** ``` <weblogic-enterprise-bean> <ejb-name>TestBean</ejb-name> <resource-description> <res-ref-name>myWorkManager</res-ref-name> <jndi-name>wm/myWorkManager</jndi-name> </resource-description> </weblogic-enterprise-bean> ``` it will look like this > **weblogic-ejb-jar.xml** ``` <weblogic-enterprise-bean> <ejb-name>TestBean</ejb-name> </weblogic-enterprise-bean> ``` your workManager reference will go to ejb-jar.xml like this. > **ejb-jar.xml** ``` <enterprise-beans> <session> <ejb-name>TestBean</ejb-name> <ejb-class>com.xxx.TestBean</ejb-class> <!-- your package com.xxx--> <resource-ref> <res-ref-name>myWorkManager</res-ref-name> <res-type>commonj.work.WorkManager</res-type> <res-auth>Container</res-auth> </resource-ref> </session> </enterprise-beans> ``` Now to get WorkManager from JNDI I'm doing ``` InitialContext ctx = new InitialContext(); this.workManager = (WorkManager) ctx.lookup("java:comp/env/myWorkManager"); ``` but I belive annotation will work equally well. ``` @Resource(name = "myWorkManager") ``` my **weblogic-application.xml** looks same as shared above ``` <weblogic> <work-manager> <name>myWorkManager</name> <ignore-stuck-threads>1</ignore-stuck-threads> </work-manager> ``` This is working for me .. let me know if needed I can share my full code. you can view your WorkManager and load on it by going to Weblogic Admin Console Home—>Deployments—>yourApp—>Monitoring(Tab)—>WorkLoad(Tab)”
BEA (together with IBM) have developed a framework specifically for managing long-running tasks in a Java EE environment. Take a look at [CommonJ](http://download.oracle.com/docs/cd/E13222_01/wls/docs92/commonj/commonj.html). The Spring Framework offers some convenience classes around this framework.
Weblogic Bea 10.0 M1 and WorkManager
[ "", "java", "jakarta-ee", "weblogic", "weblogic-10.x", "" ]
I don't want to replicate code across overloaded constructors as below. How do I refactor it? ``` /// <summary> /// Represents a pseudo-random number generator, a device that /// produces a sequence of numbers that are normally distributed. /// </summary> public class NormalDeviate : UniformDeviate { double mean; double standardDeviation; double storedValue = 0d; /// <summary> /// Initializes a new instance of the <see cref="NormalDeviate"/> class. /// </summary> /// <param name="mean">The mean.</param> /// <param name="standardDeviation">The standard deviation.</param> /// <param name="seed">The seed.</param> public NormalDeviate(double mean, double standardDeviation, ulong seed) : base(seed) { this.mean = mean; this.standardDeviation = standardDeviation; } /// <summary> /// Initializes a new instance of the <see cref="NormalDeviate"/> class. /// </summary> /// <param name="mean">The mean.</param> /// <param name="standardDeviation">The standard deviation.</param> public NormalDeviate(double mean, double standardDeviation) : base() { this.mean = mean; this.standardDeviation = standardDeviation; } } ```
Given that you can't feed the base constructor a `0` seed when no seed is provided, this would be what you want: ``` /// <summary> /// Represents a pseudo-random number generator, a device that /// produces a sequence of numbers that are normally distributed. /// </summary> public class NormalDeviate : UniformDeviate { double mean; double standardDeviation; double storedValue = 0d; /// <summary> /// Initializes a new instance of the <see cref="NormalDeviate"/> class. /// </summary> /// <param name="mean">The mean.</param> /// <param name="standardDeviation">The standard deviation.</param> /// <param name="seed">The seed.</param> public NormalDeviate(double mean, double standardDeviation, ulong seed) : base(seed) { CommonInitialization(mean, standardDeviation); } /// <summary> /// Initializes a new instance of the <see cref="NormalDeviate"/> class. /// </summary> /// <param name="mean">The mean.</param> /// <param name="standardDeviation">The standard deviation.</param> public NormalDeviate(double mean, double standardDeviation) : base() { CommonInitialization(mean, standardDeviation); } private void CommonInitialization(double mean, double standardDeviation) { this.mean = mean; this.standardDeviation = standardDeviation; } } ```
``` public ClassName(double arg1, double arg2, double arg3) : base(arg3) { _member1 = arg1; _member2 = arg2; } public ClassName(double arg1, double arg2) : this(arg1,arg2,0) { } public ClassName(double arg1) : this(arg1,0,0) { } ```
How to refactor these overloaded class constructors? (C#)
[ "", "c#", ".net", "refactoring", "" ]
I'm writing a (C++) application that utilizes a single dialog box. After setting up a message pump and handler I started wondering how I would go about propagating C++ exceptions to my original code (i.e., the code that calls `CreateDialogParam`, for instance). Here's a skeleton example of what I mean: ``` BOOL CALLBACK DialogProc(HWND, UINT msg, WPARAM, LPARAM) { if(msg == WM_INITDIALOG) //Or some other message { /* Load some critical resource(s) here. For instnace: const HANDLE someResource = LoadImage(...); if(someResource == NULL) { ---> throw std::runtime_error("Exception 1"); <--- The exception handler in WinMain will never see this! Maybe PostMessage(MY_CUSTOM_ERROR_MSG)? } */ return TRUE; } return FALSE; } //====================== void RunApp() { const HWND dlg = CreateDialog(...); //Using DialogProc if(dlg == NULL) { throw std::runtime_error("Exception 2"); //Ok, WinMain will see this. } MSG msg = {}; BOOL result = 0; while((result = GetMessage(&msg, ...)) != 0) { if(result == -1) { throw std::runtime_error("Exception 3"); //Ok, WinMain will see this. } //Maybe check msg.message == MY_CUSTOM_ERROR_MSG and throw from here? TranslateMessage(&msg); DispatchMessage(&msg); } } //====================== int WINAPI WinMain(...) { try { RunApp(); //Some other init routines go here as well. } catch(const std::exception& e) { //log the error return 1; } catch(...) { //log the error return 1; } return 0; } ``` As you can see, `WinMain` will handle "Exception 2" and "3", but **not** "Exception 1". **My fundemental question is simple; what would be an elegant way to propagate these sorts of errors to the original "calling" code?** I thought of maybe using custom messages and moving the actual `throw`-statements out to the message pump (in `RunApp()`), but I'm not sure how that would work yet as I have relatively little experience with Windows in general. Perhaps I'm looking at this situation all wrong. How do *you* usually bail out when something fatal (i.e., an acquisition of a critical resource fails, and there's no chance for recovery) when you're in the message handler?
I would stay away from registering custom Window messages for error-handling purposes. I mean this approach will work fine, but there's not really a need. By the way, your catch handler above should catch all 3 exceptions. Your dialog procedure runs on the same thread that calls CreateDialog. Creating a modeless dialog doesn't spawn off a worker thread. The modeless dialog still gets its messages via your GetMessage/Translate/Dispatch loop. There's a stack frame there, which means when you throw, it should unwind all the way out to your WinMain try/catch block. Is this not the behavior you're seeing?
AFAIK WinAPI callbacks (like window/dialog/thread procedures) must not propagate exceptions. This is because WinAPI internals (which call the callback) are not prepared to handle exceptions. They cannot be prepared because exceptions implementation is compiler specific while the code in WinAPI DLLs is fixed so it cannot handle all the possible exceptions propagation implementations. In some simple cases (especially when you compile with Visual Studio) you may observe that exceptions are propagated as would seem right. This is however a coincidence. And even if your application does not crash you are not sure if the WinAPI functions called in between did not allocate any resources which they did not released due to exception they were not prepared for. Additional layer of complexity is added by not knowing the source of the callback (in general – for some messages it can be deduced). Messages handled by your dialog procedure go through the message loop if and only if they were posted to your dialog. If they were sent then they skip the loop and are executed directly. Additionally if a message is sent then you don't know who sends the message – is it you? Or maybe Windows? Or some other window in other process trying to do something? (However this would be risky.) You don't know whether the calling site is prepared for an exception. Some way of workaround is offered by [Boost.Exception](http://www.boost.org/doc/libs/1_39_0/libs/exception/doc/boost-exception.html). The library allows to somehow store the caught exception and use (in particular rethrow) it latter. This way you could wrap your dialog procedure in a `throw { ... } catch(...) { ... }` where in catch you would capture the exception and store it for latter use. EDIT: Since C++ 11 the features of [Boost.Exception](http://www.boost.org/doc/libs/1_39_0/libs/exception/doc/boost-exception.html) to store an exception object are part of the STD. You may use `std::exception_ptr` for that. However some problems still remain. You still have to recover somehow and return some value (for messages that require return value). And you would have to decide what to do with the stored exception. How to access it? Who will do it? What will he/she do with it? In case of `WM_INITDIALOG` you may pass arbitrary parameters to the dialog procedure with this message (use appropriate form of dialog creation function) and this could be a pointer to structure which will hold the stored exception (if any). Then you could investigate that structure to see if dialog initialization failed and how. This however cannot be applied simply to any message.
Win32 Message Handler Error Propagation
[ "", "c++", "winapi", "exception", "message-queue", "" ]
I created a crystal report using test a DB. I run the report using .NET ReportDocument class. Everything works fine until I connect to the test DB. When same report is pointed to UAT DB (all required DB objects are available in UAT too), I am getting error. To fix this, I have to change the server name to UAT DB manually in the RPT file. How to fix this?
A solution is to create a system DSN (ODBC) for connecting to your target database. You can then switch the ODBC to whichever database you want (local,test,stage etc). Also, if you ensure an ODBC connection of the same name is available on all your servers, moving the report from dev->test->stage->production should be easy.
Using [push reports](http://aspalliance.com/265_Crystal_Report_for_Visual_Studio_NET.5) should solve your issue. You can set up the report to accept a strongly-typed ADO.NET Dataset, and supply that dataset at runtime.
Crystal report - Running thru .NET
[ "", "c#", ".net", "vb.net", "crystal-reports", "" ]
I have some JPEG files that I can't seem to load into my C# application. They load fine into other applications, like the GIMP. This is the line of code I'm using to load the image: ``` System.Drawing.Image img = System.Drawing.Image.FromFile(@"C:\Image.jpg"); ``` The exception I get is: "A generic error occurred in GDI+.", which really isn't very helpful. Has anyone else run into this, or know a way around it? Note: If you would like to test the problem you can [download a test image](http://www.binaryfortress.com/wp-content/uploads/2009/07/Image.jpg) that doesn't work in C#.
.Net isn't handling the format of that particular image, potentially because the jpeg data format is slightly broken or non-standard. If you load the image into GIMP and save to a new file you can then load it with the Image class. Presumably GIMP is a bit more forgiving of file format problems.
There's an exact answer to this problem. We ran into this at work today, and I was able to prove conclusively what's going on here. The JPEG standard defines a metadata format, a file that consists of a series of "chunks" of data (which they call "segments"). Each chunk starts with FF marker, followed by another marker byte to identify what kind of chunk it is, followed by a pair of bytes that describe the length of the chunk (a 16-bit little-endian value). Some chunks (like FFD8, "Start of Image") are critical to the file's usage, and some (like FFFE, "Comment") are utterly meaningless. When the JPEG standard was defined, they also included the so-called "APP markers" --- types FFE0 through FFEF --- that were supposed to be used for "application-specific data." These are abused in various ways by various programs, but for the most part, they're meaningless, and can be safely ignored, with the exception of APP0 (FFE0), which is used for JFIF data: JFIF extends the JPEG standard slightly to include additional useful information like the DPI of the image. The problem with your [image](http://www.binaryfortress.com/wp-content/uploads/2009/07/Image.jpg) is that it contains an FFE1 marker, with a size-zero chunk following that marker. It's otherwise unremarkable image data (a remarkable image, but unremarkable data) save for that weird little useless APP1 chunk. GDI+ is wrongly attempting to interpret that APP1 chunk, probably attempting to decode it as EXIF data, and it's blowing up. (My guess is that GDI+ is dying because it's attempting to actually process a size-zero array.) GDI+, if it was written correctly, would ignore any APPn chunks that it doesn't understand, but instead, it tries to make sense of data that is by definition nonstandard, and it bursts into flames. So the solution is to write a little routine that will read your file into memory, strip out the unneeded APPn chunks (markers FFE1 through FFEF), and then feed the resulting "clean" image data into GDI+, which it will then process correctly. We currently have a contest underway here at work to see who can write the JPEG-cleaning routine the fastest, with fun prizes :-) For the naysayers: That image is *not* "slightly nonstandard." The image uses APP1 for its own purposes, and GDI+ is very wrong to try to process that data. Other applications have no trouble reading the image because they rightly ignore the APP chunks like they're supposed to.
Error while loading JPEG: "A generic error occurred in GDI+."
[ "", "c#", "image", "gdi+", "" ]
I have an Orders table that stores the Ordernumber as NVarChar. We manually increment the order number by querying for the biggest order number ordering in descending order and returning the top 1 and then adding 1. We have this implemented in Microsoft CRM 4.0. e.g Order Numbers (NVarchar) ``` 99 456 32 ``` When I query the above values it returns 99 instead of 456. I want to pad all of the current order numbers to something like 000099 or 000456 using a sql script in SQL server 2005. So the above example would be ``` 000099 000456 000032 ``` What SQL script would I have to write to accomplish this?
Here's a great padding tutorial on [LessThanDot](http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/how-to-pad-positive-and-negative-number-). ``` DECLARE @Numbers TABLE (Num INT) INSERT @Numbers VALUES('1') INSERT @Numbers VALUES('12') INSERT @Numbers VALUES('123') INSERT @Numbers VALUES('1234') INSERT @Numbers VALUES('12345') INSERT @Numbers VALUES('123456') INSERT @Numbers VALUES('1234567') INSERT @Numbers VALUES('12345678') SELECT RIGHT(REPLICATE('0', 8) + CONVERT(NVARCHAR(8),Num),8) FROM @Numbers ``` This will result in: ``` 00000001 00000012 00000123 00001234 00012345 00123456 01234567 12345678 ```
**don't do it this way!** store the values as INTs. You'll be forever trapped padding with zeros if you use strings. If you decide to store the zeros in the strings, you'll still have to pad user input with zeros to query for it (or use like '%'+@x+'%', yikes!)
How do you pad a NVARCHAR field with zeros using T-SQL in a SQL Server 2005 DB?
[ "", "sql", "t-sql", "dynamics-crm", "dynamics-crm-4", "" ]
Take the following example...a page with a `ListView` and a `DataPager` used for paging the data of the `ListView`: *Code Behind:* ``` protected void Page_Load(object sender, EventArgs e) { MyList.DataSource = GetSomeList(); MyList.DataBind(); } ``` *Source:* ``` <asp:ListView ID="MyList" runat="server"> <% //LayoutTemplate and ItemTemplate removed for the example %> </asp:ListView> <asp:DataPager ID="ListPager" PagedControlID="MyList" runat="server" PageSize="10"> <Fields> <asp:NumericPagerField /> </Fields> </asp:DataPager> ``` The problem with the `DataPager` is that it is always a step-behind with the binding. For example, when the page loads it's on page number 1. Then when you click on page 3, it stays on page 1 after the postback. Then you click on page 5, and after the postback it finds itself on page 3...and after that you click on page 6, and it finds itself on page 5...and so on and so forth. Why isn't the paging working as expected?
## Solution The problem is due to the binding occuring on the `Page_Load` event. For this to work as expected, **the binding needs to happen in the `DataPager`'s `OnPreRender` event**, not in the `Page_Load`. *Source:* ``` <asp:DataPager ID="ListPager" PagedControlID="MyList" runat="server" PageSize="10" OnPreRender="ListPager_PreRender"> <Fields> <asp:NumericPagerField /> </Fields> </asp:DataPager> ``` *Code Behind:* ``` protected void Page_Load(object sender, EventArgs e) { //Binding code moved from Page_Load //to the ListView's PreRender event } protected void ListPager_PreRender(object sender, EventArgs e) { MyList.DataSource = GetSomeList(); MyList.DataBind(); } ```
I ran into this same problem, but binding everytime on datapager prerender was not an option for me. Instead, I was able to accomplish much the same thing by binding only when the paging occurred. This solution can be used as an alternative to the prerender solution by Andreas. The following worked for me: By attaching to the ListView's PagePropertiesChanged event, I was able to correct the paging issue without having to bind on every prerender of the data pager. **NOTE:** Most of the data pager properties are setup in a skin file, which is why they are not in the markup. *Markup:* ``` <asp:DataPager ID="ListPager" runat="server" PagedControlID="MyList" /> <asp:ListView ID="MyList" runat="server"> <% //LayoutTemplate and ItemTemplate removed for the example %> </asp:ListView> ``` *Code Behind:* ``` protected void Page_Load(object sender, EventArgs e) { MyList.PagePropertiesChanged += new EventHandler(MyList_PagePropertiesChanged); } /// <summary> /// Handles the situation where the page properties have changed. Rebind the data /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MyList_PagePropertiesChanged(object sender, EventArgs e) { MyList.DataSource = GetSomeList(); MyList.DataBind(); } ```
ASP.Net : DataPager Control always a step behind with paging
[ "", "c#", "asp.net", "listview", "datapager", "" ]
I have a CCounter class which holds and integer value protected by mutex. I've defined several operators like post/pre inc/dec returning an integer so I can do: ``` CCounter c(10); int i = c++; ``` but what do I do with a simple assignment like `i = c` ? I tried to define friend operator= but it gives me `operator=(int&, const CCounter&)’ must be a nonstatic member function` error. Please, advise. Thanks.
You need to define a casting operator that casts from CCounter to int. Add this member to your class: ``` operator int() const { return ...; } ```
As you have found out, the assignment operator must be a member function of a class. As ints are not classes, you can't write operator=() for them. The alternative, as others have pointed out is to write a function that converts to an int. I would strongly suggest you write a named function like ToInt() to do this, rather than using a conversion operator, which can be the source of non-obvious bugs.
Is it possible to assign object to int?
[ "", "c++", "operator-overloading", "" ]
I have tried to use Javamail to send emails. However, I received the following message: ``` javax.mail.SendFailedException: Send failure (javax.mail.MessagingException: Illegal Arguments (java.lang.IllegalArgumentException: Bad Request: )) ``` I have tried to send emails from the admin account (that I use to upload the app), as well as the user account I login to the app as. (from `UserService - getCurrentUser().getEmail()`) both failed. I'm wondering whether there's any special setting I have to setup? ``` Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); Message msg = new MimeMessage(session); UserService userService = UserServiceFactory.getUserService(); String email = userService.getCurrentUser().getEmail(); //Or //String email = "my_admin_account@gmail.com"; msg.setFrom(new InternetAddress(email)); msg.addRecipient(Message.RecipientType.TO, new InternetAddress("some_test_email@gmail.com")); msg.setSubject("Test Email"); msg.setText("Nobody"); Transport.send(msg); ```
That is really very odd. I just wrote the following sample: ``` UserService userService = UserServiceFactory.getUserService(); String thisURL = request.getRequestURI(); if (request.getUserPrincipal() != null) { response.getWriter().println("<p>Hello, " + request.getUserPrincipal().getName() + "! You can <a href=\"" + userService.createLogoutURL(thisURL) + "\">sign out</a>.</p>"); Properties props = new Properties(); Session mailSession = Session.getDefaultInstance(props, null); Message msg = new MimeMessage(mailSession); String email = userService.getCurrentUser().getEmail(); //Or //String email = "my_admin_account@gmail.com"; msg.setFrom(new InternetAddress(email)); msg.addRecipient(Message.RecipientType.TO, new InternetAddress("jesse.sightler@gmail.com")); msg.setSubject("Test Email"); msg.setText("Nobody"); Transport.send(msg); response.getWriter().println("<p>Sent email!</p>"); } else { response.getWriter().println("<p>Please <a href=\"" + userService.createLoginURL(thisURL) + "\">sign in</a>.</p>"); } ``` There were no exceptions, and I did receive the email. Are you sure there isn't more going on in the actual application?
Just scanning [the documentation on this](http://code.google.com/appengine/docs/java/mail/overview.html) I found the following: > For security purposes, the sender > address of a message must be the email > address of an administrator for the > application, or the Google Account > email address of the current user who > is signed in. The email address can > include a "reply to" address, which > must also meet these restrictions. So 'email' should at the very least be set back to your admin emailaccount, or a dedicated emailaccount added as an administrator to your project.. Other than that I see no problems with your code..
Unable to send emails on Google App Engine
[ "", "java", "google-app-engine", "jakarta-mail", "" ]
As I understand it, using XSL to generate documents has two parts: 1) An XML document which references an XSL stylesheet 2) An XSL stylesheet Let's say that I want to generate a document using XSL, and then send it to a friend. Without relying on the stylesheet being available on the internet, and without including the stylesheet as a separate file, how can I send him the document as a single file and have it just work? I suppose ideally I'd like to send the "transformed" output, not the XML or XSL itself. Can this be done?
You have a two options: 1. Do as you suggest and send your friend the transformed document (the output of the xml/xsl transformation) 2. Embed the xml/xsl in a single file as per the xslt spec ([link text](http://www.w3.org/TR/xslt#section-Embedding-Stylesheets)) If you're not sure if your friend will be able to process the xml/xsl file himself, then you are really only left with option 1
You need an xslt processor. This takes xml and xsl files and process them into their output (typically html, text, or xml). Some common ones are: * XSLTProc <http://xmlsoft.org/XSLT/xsltproc2.html> (for windows <http://www.sagehill.net/docbookxsl/InstallingAProcessor.html>) * MSXSL <http://www.microsoft.com/downloads/details.aspx?FamilyID=2FB55371-C94E-4373-B0E9-DB4816552E41&displaylang=en> * Xalan <http://xalan.apache.org/> * Saxon <http://saxon.sourceforge.net/> * XT <http://www.blnz.com/xt/index.html> You can then take the output html, text, or xml file, and pass that on to your friend.
How do I generate an HTML file using XSL?
[ "", "c++", "xml", "winapi", "xslt", "" ]
I have a webpage which I would like users to be able to send to a friend at the click of a button. I am currently using Chilkat's MailMan but I keep getting intermittent problems with it. It seems occassionaly on the first attempt to mail it throws a null pointer exception. Then if try the exact same page again it sends no problem. * Are there any other components out there that will do what I am trying to do? * Would it be easier to right my own light weight component to do it? * Has anyone had the above problem that can be solved easily and then I don't have to worry about the above? **EDIT:** Maybe I should clear something up. I know how to send emails. That is not the problem. The Chilkat component I was using could take in a webpage and put it into an email and send it. The person that receives it then has an email with all the CSS included and the pictures and everything in the email.
This is actually not a trivial exercise. What you want to do, is download the HTML (which is the easy part). You then have to parse it, and extract all of the css references, and image references, and either: 1. Embed them into the email, or 2. Convert all links to absolute links. When you look at all the bad HTML out there, you find out this isn't trival. The reason why I know this, is I wrote this functionality into aspNetEmail ([www.aspNetEmail.com](http://www.aspNetEmail.com)), and had to account for all sorts of bad HTML.
Could you use the WebClient class to get the webpage that the user is requesting? You'd want to change any relative links to absolute links (e.g. from "/images/logo.gif" to "<http://myapp.com/images/logo.gif>"), then take the output and use that as the body of the MailMessage object i.e. ``` public void MailToAFriend(string friendMailAddress, Uri uriToEmail) { MailMessage message = new MailMessage(); message.From = "your_email_address@yourserver.com"; message.To = friendEmailAddress; message.Subject = "Check out this awesome page!"; message.Body = GetPageContents(uriToEmail); SmtpClient mailClient = new SmtpClient(); mailClient.Send(message); } private string GetPageContents(Uri uri) { var webClient = new WebClient(); string dirtyHtml = webClient.DownloadString(uri); string cleanedHtml = MakeReadyForEmailing(dirtyHtml); return cleanedHtml; } private string MakeReadyForEmailing(string html) { // some implementation to replace any significant relative link // with absolute links, strip javascript, etc } ``` There's lots of resources on Google to get you started on the regex to do the replacement.
Any suggestions for components to implement "Send to a friend"?
[ "", "c#", "asp.net", "" ]
I've been exploring what cryptographic modules are available to Python, and I've found 3: ezPyCrypt, yawPyCrypt and KeyCzar (which actually supports a few languages, but Python is included amongst them). The first two rely on the PyCrypto module. Are there choices I am missing? Is there a clear front-runner for ease and features or does it simply come down to a manner of one's comfort level? I'm currently leaning towards KeyCzar, with ezPyCrypt close behind. I would be using the library for digital signature signing and verification, and potentially for key creation (although I won't cry if I have to make a call to something else for that functionality). I am using Python 3.x and have access to GPG.
If you are in an environment which includes GnuPG and Python >= 2.4, then you could also consider a tool such as [python-gnupg](https://bitbucket.org/vinay.sajip/python-gnupg). (Disclaimer: I'm the maintainer of this project.) It leaves the heavy lifting to `gpg` and provides a fairly straightforward API. Overview of API: ``` >>> import gnupg >>> gpg = gnupg.GPG(gnupghome='/path/to/keyring/directory') >>> gpg.list_keys() [{ ... 'fingerprint': 'F819EE7705497D73E3CCEE65197D5DAC68F1AAB2', 'keyid': '197D5DAC68F1AAB2', 'length': '1024', 'type': 'pub', 'uids': ['', 'Gary Gross (A test user) ']}, { ... 'fingerprint': '37F24DD4B918CC264D4F31D60C5FEFA7A921FC4A', 'keyid': '0C5FEFA7A921FC4A', 'length': '1024', ... 'uids': ['', 'Danny Davis (A test user) ']}] >>> encrypted = gpg.encrypt("Hello, world!", ['0C5FEFA7A921FC4A']) >>> str(encrypted) '-----BEGIN PGP MESSAGE-----\nVersion: GnuPG v1.4.9 (GNU/Linux)\n \nhQIOA/6NHMDTXUwcEAf ... -----END PGP MESSAGE-----\n' >>> decrypted = gpg.decrypt(str(encrypted), passphrase='secret') >>> str(decrypted) 'Hello, world!' >>> signed = gpg.sign("Goodbye, world!", passphrase='secret') >>> verified = verified = gpg.verify(str(signed)) >>> print "Verified" if verified else "Not verified" 'Verified' ```
A new cryptography library for Python has been in rapid development for a few months now. The 0.2.1 release just happened a few days ago. <https://cryptography.io/en/latest/> It is mainly a CFFI wrapper around existing C libraries such as OpenSSL. It is distributed as a pure python module and supports CPython versions 2.6 - 3.3 as well as PyPy. It is also the upstream of the refactored pyOpenSSL package. It aims to expose high-level "recipes" that makes cryptography as idiot-proof as possible as well as primitives that should only be used with the appropriate caution. Symmetric algorithms (including AES-GCM) is very well supported and asymmetric algorithms such as RSA and DSA should be coming in the next few releases. Other notable algorithms that are supported includes PBKDF2, HKDF, HOTP and TOTP.
Recommended Python cryptographic module?
[ "", "python", "cryptography", "" ]
Is it considered as a good practice to pick Unicode string over regular string when coding in Python? I mainly work on the Windows platform, where most of the string types are Unicode these days (i.e. .NET String, '\_UNICODE' turned on by default on a new c++ project, etc ). Therefore, I tend to think that the case where non-Unicode string objects are used is a sort of rare case. Anyway, I'm curious about what Python practitioners do in real-world projects.
From my practice -- use unicode. At beginning of one project we used usuall strings, however our project was growing, we were implementing new features and using new third-party libraries. In that mess with non-unicode/unicode string some functions started failing. We started spending time localizing this problems and fixing them. However, some third-party modules doesn't supported unicode and started failing after we switched to it (but this is rather exclusion than a rule). Also I have some experience when we needed to rewrite some third party modules(e.g. SendKeys) cause they were not supporting unicode. If it was done in unicode from beginning it will be better :) So I think today we should use unicode. P.S. All that mess upwards is only my hamble opinion :)
As you ask this question, I suppose you are using Python 2.x. Python 3.0 changed quite a lot in string representation, and all text now is unicode. I would go for unicode in any new project - in a way compatible with the switch to Python 3.0 (see [details](http://docs.python.org/3.0/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit)).
Should I use Unicode string by default?
[ "", "python", "unicode", "" ]
i have an overloaded operator << trying to make it work like this ``` mystream<<hex<<10; ``` i have overloaded method ``` mytream& operator<<(ios_base& (*m) ios_base&) ``` This gets called whenever hex is encountered cause the parameter passed in the method is a function pointer of type same as hex or like some other output manipulators like dec, oct. i have two problems 1) how do i retrieve the parameter the hex would be operating on, in this example 10 2) how do i know that the << operator is being called for hex and not other manipulator function like oct and dec Thanks
1) hex is not operating on the parameter 10. `<<` operators associate left-to-right, which means your code is the same as: ``` (mystream<<hex)<<10; ``` So your overload has to return an object which, when 10 is shifted into it, prints in hex (or if not prints, writes data somewhere). As everyone says, this is done by saving flags in the stream object itself, then returning `*this`. The reason flags are used is precisely because the "10" is not available yet, since the second `<<` has not been evaluated yet. The first `<<` operator call cannot print anything - it just has to get ready for when the second one is called. 2) hex is a function. It can be compared with other functions: ``` ostream &operator<<(ostream &s, ios_base& (*m)(ios_base &)) { if (m == hex) { } else if (m == oct) { } else if (m == dec) { } } ``` Except you don't normally want to do that, you want the default behaviour, which is something like: ``` ostream &operator<<(ostream &s, ios_base& (*m)(ios_base &)) { return m(s); } ``` (I may be wrong on that, I've never looked at the implementation, but the general idea is that the operator calls the manipulator function, and the manipulator (the clue's in the name) manipulates the stream). `std::hex` sets the `std::ios::hex` format flag on its parameter. Then in your `operator<<(int)` override, if you have one, check the format flags by calling `flags()`. 3) Manipulators which take paramers are functions too, but their return types are unspecified, meaning it's up to the implementation. Looking at my gcc `iomanip` header, `setw` returns `_Setw`, `setprecision` returns `_Setprecision`, and so on. [The Apache library does it differently](http://stdcxx.apache.org/doc/stdlibug/33-3.html), more like the no-args manipulators. The only thing you can portably do with parameterized manipulators is apply them to an iostream with `operator<<`, they have no defined member functions or operators of their own. So just like `hex`, to handle `setw` you should inherit from `std::ios_base`, rely on the `operator<<` implementation provided by your library, then when you come to format your data, examine your own width, precision, etc, using the `width()`, `precision()`, etc, functions on `ios_base`. That said, if for some bizarre reason you needed to intercept the standard `operator<<` for these manipulators, you could probably bodge something together, along these lines: ``` template <typename SManip> mystream &operator<<(mystream &s, SManip m) { stringstream ss; // set the state of ss to match that of s ss.width(s.width()); ss.precision(s.precision()); // etc ss << m; // set the state of s to match that of ss s.width(ss.width()); s.precision(ss.precision()); // etc return s; } ``` I do consider this a bodge, though. You're not really supposed to interfere with stream manipulators, just let your base class do the work and look up the results.
When `operator<<` gets called with `hex` or `oct` or `dec`, set a flag in your `mystream` object. When `operator<<` is called with a number, check to see if any of these flags are set. If so, convert the number to hex/octal/decimal and display it.
An overloaded operator takes function pointer as parameter, how do i retrieve arguments of function pointer
[ "", "c++", "operator-overloading", "" ]
> **Possible Duplicate:** > [How to check if internet connection is present in java?](https://stackoverflow.com/questions/1402005/how-to-check-if-internet-connection-is-present-in-java) I want to see if anyone has an easy way of detecting if there is an internet connection when using Java. The current app used the "InternetGetConnectedState" method in the WinInit DLL for windows, but my app needs to be cross-platform for mac operation and this way will not work. I do not know JNI at all either to use DLLs in Java and it became frustrating fast. Only ways I could think of were tring to open a URL connection to a website and if that fails, return false. My other way is below, but I didn't know if this was generally stable. If I unplug my network cable i do get an UnknownHostException when trying to create the InetAddress. Otherwise if the cable is connected I get a valid InetAddress object. I didnt test the below code on a mac yet. Thanks for any examples or advice you can provide. UPDATE: Final code block is at the bottom. I decided to take the advice of an HTTP request (in this case Google). Its simple and sends a request to the site for data to be returned. If I cannot get any content from the connection, there is no internet. ``` public static boolean isInternetReachable() { try { InetAddress address = InetAddress.getByName("java.sun.com"); if(address == null) { return false; } } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } return true; } ``` Final Code Block: ``` //checks for connection to the internet through dummy request public static boolean isInternetReachable() { try { //make a URL to a known source URL url = new URL("http://www.google.com"); //open a connection to that source HttpURLConnection urlConnect = (HttpURLConnection)url.openConnection(); //trying to retrieve data from the source. If there //is no connection, this line will fail Object objData = urlConnect.getContent(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } return true; } ```
That's a perfectly reasonable approach to solving the problem. The bad thing is that you are really testing DNS rather than testing the whole network, but in practice you can often get by with treating those as equivalent. The other thing to remember, is that you will need to set a system property to turn off dns caching in the java runtime. Otherwise it may continue to report that the network is up based upon cached data (even though it is down). Another approach would be to actually open an HTTP request to some network address such as this every so often.
I must add that although the final code block given above is good, it has one flaw - it is possible for it to take a very long time to contact the address specified, but the address is still reachable. In my instance when testing with one address the method would return true, but take 10 seconds or longer to get a response. In this case the server was reachable, but not for any useful purposes since the connection was so slow. This occurs because the default timeout for `HttpURLConnection` is **0**, or infinite. For this reason I'd recommend you do the checking off the UI thread, and add `urlConnect.setConnectTimeout(1000);` **before** calling `urlConnect.getContent();` This way you know the address is reachable, and that it won't take 5 years to download a 10k file. (You might of course want to change the the timeout time to suit your needs) Also I'd recommend not checking a generic address (google.com etc) unless your program generally accesses more than a few domains. If you're just accessing one or two then check that domain.
Detect internet Connection using Java
[ "", "java", "internet-connection", "" ]
I have an `enum` in Java for the cardinal and intermediate directions: ``` public enum Direction { NORTH, NORTHEAST, EAST, SOUTHEAST, SOUTH, SOUTHWEST, WEST, NORTHWEST } ``` How can I write a `for` loop that iterates through each of these `enum` values?
# `.values()` You can call the `values()` method on your enum. ``` for (Direction dir : Direction.values()) { // do what you want } ``` This `values()` method is [implicitly declared by the compiler](http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.9.3). So it is not listed on [`Enum`](http://docs.oracle.com/javase/8/docs/api/java/lang/Enum.html) doc.
All the constants of an enum type can be obtained by calling the implicit `public static T[] values()` method of that type: ``` for (Direction d : Direction.values()) { System.out.println(d); } ```
A for-loop to iterate over an enum in Java
[ "", "java", "loops", "for-loop", "enums", "" ]
I'm rewriting its XML itemSource on the fly and want it to use the new data right away...
You should use an ObervableCollection. When this collection is updated, the ListView is updated. But if for any reason you don´t want to use one, use: ``` listView.InvalidateProperty(ListView.ItemsSourceProperty); ``` or ``` listView.ItemsSource = listView.ItemsSource; ``` Check [A more elegant ListView requery](https://stackoverflow.com/questions/1406542/a-more-elegant-listview-requery) for more info.
hmm... ``` listView.ItemsSource = listView.ItemsSource? ``` or you could trigger the PropertyChanged event on the property of your viewmodel in case you are using MVVM.
How do you force a WPF ListView to Requery its ItemSource?
[ "", "c#", "wpf", "xml", "listview", "refresh", "" ]
How do I best design a database where I have one table of players (with primary key **player\_id**) which I want to pair into teams of two so that the database can enforce the constraint that each team consists of *exactly two* players and each player is in *at most one* team? I can think of two solutions, but both I'm not too happy about. One possibility is to have two columns **player1\_id** and **player2\_id** that are *unique* foreign keys pointing to the **player\_id** column in the player table. An additional check is needed so that no player is at the same time player1 of one team and player2 of a second team. The other possibility that comes to my mind is to connect the player table and the team table with a team membership table that has a *unique* foreign key to the **player\_id** column in the player table and a second foreign key pointing to the primary key of the team table. Here a check has to be added that every team has exactly two members. Is there a better design that simplifies the checking of the constraints? If it matters: the database I'm using is PostgreSQL 8.4 and I prefer its powerful [rule system](http://www.postgresql.org/docs/8.4/static/rules.html) to triggers wherever possible. EDIT: A solution based on the answer of AlexKuznetsov It doesn't feel perfect to me yet, but I like it much better than what I had before. I modified Alex' solution since I don't want to have a foreign key from players to teams, as there is an application phase where players can enroll. ``` create table TeamMemberships( player_id int not null unique references Players(player_id), team_id int not null references Teams(team_id), NumberInTeam int not null check(NumberInTeam in (0,1)), OtherNumberInTeam int not null, -- check(OtherNumberInTeam in (0,1)) is implied check(NumberInTeam + OtherNumberInTeam = 1) foreign key (team_id, OtherNumberInTeam) references TeamMemberships(team_id, NumberInTeam), primary key (team_id, NumberInTeam) ); ``` This definition makes sure that team memberships come in couples (and will be inserted pairwise). Now players can be in at most one team and teams can have exactly 0 or exactly 2 players. To ensure that each team has members I could add a foreign key in the team table that points to any of its two memberships. But like Erwin I'm not a fan of deferred constraint checking. Any ideas how to improve with respect to this? Or is there a completely different, better approach? PS: The methods works also for teams with n>2 players. One just has to replace OtherNumberInTeam by NextNumberInTeam with the value (i.e. constraint) NumberInTeam+1 mod n.
I don't know if this can work on Postgress, but here is a SQL Server solution: ``` CREATE TABLE dbo.Teams(TeamID INT NOT NULL PRIMARY KEY); GO CREATE TABLE dbo.Players(PlayerID INT NOT NULL PRIMARY KEY, TeamID INT NOT NULL FOREIGN KEY REFERENCES dbo.Teams(TeamID), NumberInTeam INT NOT NULL CHECK(NumberInTeam IN (1,2)), TeamMateID INT NOT NULL, TeamMatesNumberInTeam INT NOT NULL, -- if NumberInTeam=1 then TeamMatesNumberInTeam must be 2 -- and vise versa CHECK(NumberInTeam+TeamMatesNumberInTeam = 3), UNIQUE(TeamID, NumberInTeam), UNIQUE(PlayerID, TeamID, NumberInTeam), FOREIGN KEY(TeamMateID, TeamID, TeamMatesNumberInTeam) REFERENCES dbo.Players(PlayerID, TeamID, NumberInTeam) ); INSERT INTO dbo.Teams(TeamID) SELECT 1 UNION ALL SELECT 2; GO ``` -- you can only insert players in complete pairs ``` INSERT INTO dbo.Players(PlayerID, TeamID, NumberInTeam, TeamMateID, TeamMatesNumberInTeam) SELECT 1,1,1,2,2 UNION ALL SELECT 2,1,2,1,1; ``` You can try inserting a single player, or deleting a player from a team, or inserting more than two players per team - all will fail due to a complete set of constraints. Note: the practice in SQL Server is to explicitly name all constraints. I did not name my constraints just in case that is not compatible with Postgres.
This sounds like something that would be much easier to enforce in a user interface than it would in the database. When adding players to teams, don't allow more than 2 players to be added, and only allow players not already in a team to be added.
Database design for constraint enforcing pairing
[ "", "sql", "database-design", "postgresql", "" ]
Do special processing for a type in a generic class Pinnew member dan neely 19mins ago I'm trying to roll up some old (originally .net 1.1) abstract classes into generics. The classes in question all provide similar functionality for a data object of a specific type. For the most part things are going well, but I've ran into a few places where one one of the data objects is of a type that needs extra processing in one method beyond what all the other types need. I can check the type of T to see if it's the type I need to do the special processing for, but the cast from T to SpecialType won't compile. Is there a different way I can do this, or is what I want to do impossible? ``` class MyGenericClass : ICloneable where T: class, new() { private T m_storedClass; ... private DoStuff() { //do stuff for all types //objects of SpecialType need extra stuff done. if (typeof(T) == typeof(SpecialType)) { //compiler error: Error Cannot convert type 'T' to 'SpecialType' ((SpecialType)m_storedClass).SpecialString = "foo"; } } ```
How about something like this: ``` interface ISomething { void DoSomething(); } class NormalType : ISomething { // ... public void DoSomething() { /* nothing to do */ } } class SpecialType : ISomething { // ... public void DoSomething() { this.SpecialString = "foo" } } class MyGenericClass : ICloneable { private ISomething m_storedClass; private DoStuff() { // ... m_storedClass.DoSomething(); } } ```
The following compiles fine. ``` if (typeof(T) == typeof(SpecialClass)) { (this.m_storedClass as SpecialClass).SpecialOperation(); } ``` Casting to `Object` first is another solution. ``` if (typeof(T) == typeof(SpecialClass)) { ((SpecialClass)((Object)this.m_storedClass)).SpecialOperation(); } ``` Just to note, the check could also be rewritten to the following. ``` if (this.m_storedClass is SpecialClass) { (this.m_storedClass as SpecialClass).SpecialOperation(); } ``` Or using only a single `as` operator including a non-null check in the condition for free. ``` SpecialClass special = this.m_storedClass as SpecialClass; if (special != null) { special.SpecialOperation(); } ```
Do special processing for a type in a generic class
[ "", "c#", "generics", "casting", "" ]
If I have: ``` class foo implements Cloneable ``` and then do: ``` bar = new foo(); bar.clone(); ``` I get a shallow copy without needing to write any `bar.clone()` code like I normally would need to do when I implement an interface. My understanding is that an interface's functions must be filled in by the class implementing it, and `Object.clone()` has no implementation (as per the docs, "The class Object does not itself implement the interface Cloneable") So where does my shallow clone come from? Where is the code that implements `bar.clone()` if `Object.clone()` has no implementation? I'm confused.
Be *very careful* using clone. In fact, I would avoid it completely. I have *never* needed it. BUT... that being said, the best discussion of the topic I have ever read is by Joshua Bloch, in Effective Java. Read Item 11: "Override clone judiciously". PLEASE do yourself a favor and read that item. I actually recommend reading that entire chapter (and the rest of the book). Everything you need to know about clone and why I caution you about it is in there. Hope this helps.
Object.clone() has an implementation: <http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html#clone()> This link explains the Cloneable interface: <http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Cloneable.html> An object must implement the Cloneable interface in order to call the clone() method, otherwise, it throws a CloneNotSupportedException. By definition, all classes in Java extend the base Object class, and Object class has a default clone() method, even though Object itself does not implement Cloneable. The Object class's clone() method will be called if you do not override it yourself.
Confusion about cloneable interface and object.clone() in java
[ "", "java", "cloneable", "" ]
I'm trying to get the total height of a page using JavaScript so I can check if the page is long enough to display something, however in my testing I am unable to get the total height of a page. I've looked around on the Internet but things like this don't seem to be well documented, as all I can find is `scrollHeight`, which, as I might mention, doesn't work. Any way to use JavaScript to find it?
Without a framework: ``` var _docHeight = (document.height !== undefined) ? document.height : document.body.offsetHeight; var _docWidth = (document.width !== undefined) ? document.width : document.body.offsetWidth; ```
`document.documentElement.scrollHeight` is working ok for me in the latest version of Internet Explorer, Chrome, Firefox and Safari.
Total height of the page
[ "", "javascript", "" ]
I am using codeigniter php MVC framework to develop a web application. I have an input textarea that I would like to validate the input on. Basically it is similar to the textarea that I am typing in right now for stackoverflow, minus most (maybe all) of the formatting features that it has. Is there a simple built in way of doing this in codeigniter? If not, what would be the best way to approach this? Basically I want the input filtered and formatted properly both before writing to the database and also for retrieving the text for display on the page. I assume I would need all the basic regex checks and character escaping (like double quotes etc.) as well as sql injection protection. Thanks in advance!
you can use the same [SO editor](http://wmd-editor.com/) or [markdown](http://daringfireball.net/projects/markdown/) or a [regular WYSIWYG](http://tinymce.moxiecode.com/) for user's input. Regarding security or sql injection, look at [html purifier](http://htmlpurifier.org/comparison). you have a nice [comparative](http://htmlpurifier.org/comparison) here that can help you to see which one is the best for you... remember that more rules to check usually means more overhead
CodeIgniter has its own Form Validation library. See [link text](http://codeigniter.com/user_guide/libraries/form_validation.html). It "... provides a comprehensive form validation and data prepping class that helps minimize the amount of code you'll write." Of course, it is server-side validation. You might want to look at jQuery's Validation plugin for your client-side validations. See [link text](http://docs.jquery.com/Plugins/Validation).
Input checking for php. Best library/framework?
[ "", "php", "codeigniter", "" ]
I've developed a random string generator but it's not behaving quite as I'm hoping. My goal is to be able to run this twice and generate two distinct four character random strings. However, it just generates one four character random string twice. Here's the code and an example of its output: ``` private string RandomString(int size) { StringBuilder builder = new StringBuilder(); Random random = new Random(); char ch; for (int i = 0; i < size; i++) { ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))); builder.Append(ch); } return builder.ToString(); } // get 1st random string string Rand1 = RandomString(4); // get 2nd random string string Rand2 = RandomString(4); // create full rand string string docNum = Rand1 + "-" + Rand2; ``` ...and the output looks like this: UNTE-UNTE ...but it should look something like this UNTE-FWNU How can I ensure two distinctly random strings?
You're making the Random instance in the method, which causes it to return the same values when called in quick succession. I would do something like this: ``` private static Random random = new Random((int)DateTime.Now.Ticks);//thanks to McAden private string RandomString(int size) { StringBuilder builder = new StringBuilder(); char ch; for (int i = 0; i < size; i++) { ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))); builder.Append(ch); } return builder.ToString(); } // get 1st random string string Rand1 = RandomString(4); // get 2nd random string string Rand2 = RandomString(4); // creat full rand string string docNum = Rand1 + "-" + Rand2; ``` (modified version of your code)
You're instantiating the `Random` object inside your method. The `Random` object is [seeded from the system clock](http://msdn.microsoft.com/en-us/library/h343ddh9.aspx), which means that if you call your method several times in quick succession it'll use the same seed each time, which means that it'll generate the same sequence of random numbers, which means that you'll get the same string. To solve the problem, move your `Random` instance outside of the method itself (and while you're at it you could get rid of that crazy sequence of calls to `Convert` and `Floor` and `NextDouble`): ``` private readonly Random _rng = new Random(); private const string _chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; private string RandomString(int size) { char[] buffer = new char[size]; for (int i = 0; i < size; i++) { buffer[i] = _chars[_rng.Next(_chars.Length)]; } return new string(buffer); } ```
Random String Generator Returning Same String
[ "", "c#", "random", "" ]
(Assuming the network folders/permissions are correctly set up and working in Windows, and a 'default' PHP setup...) Is it possible to use UNC network paths [like `\\ServerName\Folder\file.txt`] in PHP's functions like `file_get_contents()`, `fopen()`, etc? And/or, what special cases allow/disallow this?
UNC paths should "**WORK**" if permissions are set properly. And the network folders are allowed to be accessed by apache user, then there won't be any problem. In these scenarios **open\_basedir** creates problems, just keep an eye on that
PHP absolutely permits UNC paths. You may have issues regarding which user is actually executing the code. If it is Apache running as a service then the user will be whatever user is listed in the entry for the windows service. if it is IIS then the user is typically IUSR\_machineName. If it is as a console then it is the currently executing user.
On Windows, can you use UNC like paths to files in PHP, for functions like file_get_contents(), etc?
[ "", "php", "unc", "" ]
I am porting an application from Qt3 to Qt4, and need a Qt4 replacement for QApplication::mainWidget() which used to return the top-level widget in Qt3. Does anyone know how to do this in Qt4?
Technically, any widget initialized with NULL is a top level widget so QApplication shouldn't assume that one of them is better than another. The way I usually do it is to save a pointer to the "real" main widget somewhere, even a global variable or a singleton and reference it when needed.
I think [topLevelWidgets()](http://doc.trolltech.com/4.5/qapplication.html#topLevelWidgets) is as close at it can be. Edit: Yup. Qt4 added complexity (and power). There is no application wide MainWidget anymore. Many QMainWindows can be created and shown, and hidden, and shown again. This is a good thing, though :) As shoosh noticed, QT3 behaviour can be easily simulated with global variable (yuck!) or QApplication subclass.
What did QWidget* QApplication::mainWidget() become in Qt4?
[ "", "c++", "qt4", "" ]
Inside of a stored procedure, I populate a table of items (#Items). Just basic information about them. However for each item, I need to make sure I can sell them, and in order to do that I need to perform a whole lot of validation. In order to keep the stored procedure somewhat maintainable, I moved the logic into another stored procedure. What would be the best way to call the stored procedure for each item in the temp table? The way I have it now, I apply an identity column and then just do a while loop, executing the stored procedure for each row and inserting the validation result into a temporary table. (#Validation) However now that logic has changed, and in between the creation of #Items and the execution of the loop, some records are deleted which screws up the while loop, since the Identity no longer equals the counter. I could handle that by dropping the identity column and reapplying it before the while loop, but I was just wondering if there was a better way. Is there a way to get a specific row at an index if I apply an order by clause? I know I could do a cursor, but those are a pain in the ass to me. Also performance is somewhat of a concern, would a fastforward readonly cursor be a better option than a while loop? The number of rows in the #Items table isn't that large, maybe 50 at most, but the stored procedure is going to be called quite frequently.
1. Turn your validation stored procedure into a user defined function that accepts an item id or the data columns needed to validate an item record 2. Create the temp table 3. Insert all your items 4. Write a delete query for the temp table that calls your new UDF in the WHERE clause.
I agree that if you can do it set-based then do it that way. Perhaps put the validation into a user-defined function instead of a sproc to enable that. Which *may* pave the way for you to be able to do it set-based. e.g. ``` SELECT * FROM SomeTable WHERE dbo.fnIsValid(dataitem1, dataitem2....) = 1 ``` However, I know this is may not be possible depending on your exact scenario, so... **Correction edit based on now understanding the IDENTITY/loop issue:** You can use ROW\_NUMBER() in SQL 2005 to get the next row, doesn't matter if there are gaps in the IDENTITY field as this will assign a row number to each record ordered by what you tell it: -- Gets next record SELECT \* FROM ( SELECT ROW\_NUMBER() OVER(ORDER BY IDField ASC) AS RowNo, \* FROM #temptable ) s WHERE s.RowNo = @Counter
What would be a better way to handle this sql logic?
[ "", "sql", "sql-server-2005", "" ]
I have ``` interface FooI class FooA implements FooI class FooB implements FooI class FooC implements FooI ``` I wrote a class "Handler" that has the following methods ``` static double handle(FooA f) static double handle(FooB f) static double handle(FooI f) ``` and I have a function like the following: ``` void caller(FooI f) { Handler.handle(f); } ``` with f just being known as a class implementing FooI. However f is an instance of FooA Instead of calling the method for FooA, the method for FooI is called. When I use f.getClass().getName() I get the correct class name (FooA). I am confused because I expected the best-suited method to get called, namely the one for FooA. I wanted to use the FooI method as a fallback to handle classes that could be implemented later, and I also want to handle f without having one big function where I am doing **instanceof** checks for all currently known classes implementing my interface. What would be a good approach to do this?
Overload resolution is done at *compile time* rather than *execution time* in Java. The signature was picked based on the compile-time type of your variable. Only *overrides* are determined at execution time. A common solution for this in languages like Java is to use [double dispatch](http://en.wikipedia.org/wiki/Double_dispatch) and the [visitor pattern](http://en.wikipedia.org/wiki/Visitor_pattern). Personally I'm not a huge fan of this. I prefer to try to design my way around it. That's not always possible, of course, but it's worth at least attempting.
You expect that the JVM seaches for the best fitting method **at run time** but that doesn't happen, actually. Instead the method to call is selected during compile time, when the only known information is that f is a class that implements FooI. The best approach for that problem, the one that avoids the instanceof checks, might be moving the "handle" method into those classes FooA, FooB, FooI.
Java method override/interface problem
[ "", "java", "interface", "" ]
Is there a faster way to select the distinct count of users from a table? Perhaps using row\_number, partitioning, or cross apply? I just can't think of it right now. Example: ``` Table UsageLog UserId Date StoreNumber Alice 200901 342 Alice 200902 333 Alice 200902 112 Bob 200901 112 Bob 200902 345 Charlie 200903 322 ``` Here's my current query: ``` select count(distinct userID), date from UsageLog where date between 200901 and 200902 group by date ``` My actual table has millions of rows and all columns are actually integers. Is there a faster way to get the list of users? **Edit**: I already have nonclustered indexes on all individual columns. For some reason, the execution plan shows that I am still doing a table scan. I guess I should create a clustered index on Date. I'll see how that works...
SELECT DISTINCT() is the way to go. The problem is that you are hitting the `date` [index tipping point](http://www.sqlskills.com/BLOGS/KIMBERLY/post/The-Tipping-Point-Query-Answers.aspx), so your plan goes for the clustered index scan instead. See the link for Kimberley L. Tripp article what a 'tipping point' is. You need a covering index: ``` CREATE INDEX idx_UsageLog_date_user_id ON UsageLog(date) INCLUDE (userID); ``` Clustered index will also work, but has other side effects as well. If the clustered index on `date` is OK with the rest of your data access patterns, then is better than the covering index I propose. **Update:** The reverse order index you tried on `(userID, date)` also works, will range seek each userID. In fact is better than the `(date, userID)` or `(date) INCLUDE (userID)` because it returns the userIDs pre-sorted so the DISTINCT does not introduce the additional sort. Still I recommend going over the link I posted to understand why 'index on each individual columns' was not helping.
Overall I have not found any way that is faster than what you have there, COUNT(DISTINCT UserId) is a pretty basic query. Your biggest thing here would be to ensure that you have an index on the table that works for the "Date" column and the UserId column
Another way to select count(distinct userID) from a table?
[ "", "sql", "sql-server", "optimization", "" ]
I've compiled my source with java version 1.6 using the parameters *-source 1.5* and *-target 1.5*, and the compiler doesnt complain at all. Still, the application won't run with java 1.5 due to missing methods. Ofcourse I could rewrite some of my source code to be 1.5 compliant, but what I don't understand is; shouldn't the java bytecode in the bottom be "frontwards" compliant? Aren't the methods converted into bytecode? Is it possible to compile the 1.6 libs/methods (formely String.isEmpty()) to 1.5 bytecode and pack it all into the archive?
The full set of command line options you need are: ``` java -source 1.5 -target 1.5 -bootclasspath /usr/jdk/jdk1.5.0_17/jre/lib/rt.jar ``` (Change bootclasspath to however your machine is setup.) Of course, APIs enhancements in 1.6 will not be in 1.5. 1.5 is most of its way through its End of Service Life period, so you might want to consider a 1.6 minimum anyway.
If you mean base Java library methods, then no, those methods are not converted to byte code when you compile; they've already been compiled to byte-code by Sun (or the third-party JVM distributer) and installed on your operating system. They are *referenced* and used by your compiled code.
Java and "frontwards" compatiblity question
[ "", "java", "compatibility", "bytecode", "" ]
I asked a similar question a couple of days ago, but I'm looking for more insight. I'm getting an AccessViolationException when I add a string to my program: ``` Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. at _cexit() at <CrtImplementationDetails>.LanguageSupport._UninitializeDefaultDomain(Void * cookie) at <CrtImplementationDetails>.LanguageSupport.UninitializeDefaultDomain() at <CrtImplementationDetails>.LanguageSupport.DomainUnload(Object source, EventArgs arguments) at <CrtImplementationDetails>.ModuleUninitializer.SingletonDomainUnload(Object source, EventArgs arguments) ``` The program has a bunch of const std::string's at the top level: ``` const std::string caseDelimitedOption = "CaseDelimited"; const std::string endOfLineOption = "EndOfLine"; const std::string functionNameDelimitWordsOption = "FunctionNameDelimitWords"; const std::string functionNameStartCaseOption = "FunctionNameStartCase"; const std::string indentStringOption = "IndentString"; const std::string lowerCaseOption = "LowerCase"; const std::string newLineBetweenDoAndWhileOption = "NewLineBetweenDoAndWhile"; const std::string nextLineOption = "NextLine"; const std::string nextLineAsWellAsCloseParenOption = "NextLineAsWellAsCloseParen"; const std::string noBracesAroundSingleStatementBlockOption = "NoBracesAroundSingleStatementBlock"; const std::string openBraceLocationOption = "OpenBraceLocation"; const std::string underscoreDelimitedOption = "UnderscoreDelimited"; const std::string upperCaseOption = "UpperCase"; const std::string whiteSpaceBeforeLeadingCmntOption = "WhiteSpaceBeforeLeadingComment"; ``` If I replace last string with: ``` const std::string whiteSpaceBeforeLeadingCmntOption = ""; //"WhiteSpaceBeforeLeadingComment"; ``` then the exception goes away. Is this just extra memory (from the string) hitting some bad memory that was caused elsewhere in my program? Or is the exception related to the string? Thanks for any help, Joe
I assume these strings are global variables. Are you trying to access these strings from the constructor of another global variable (or from some method that is called before main is entered)? If this is the case you are suffering from the probelem that global variable initialization order is undefined across multiple compilation units. There are a few solutions but more information about your application would probably be useful. First test to see if main is even entered. I would think that it working with the empty string is the result of some compiler optimization trick.
Try ``` valgrind --leak-check=full your.exe ``` and remember to compile your application with -g to get source code line in the executable.
AccessViolationException when string is too long (C++)
[ "", "c++", "string", "access-violation", "" ]
I want to check internal web pages, so I cannot use the [W3C validation](http://jigsaw.w3.org/css-validator/) service directly. I managed to run the XHTML validator locally, however, I have some problems with the css-validator. I do not really want to setup [Tomcat](http://tomcat.apache.org/) or [Jigsaw](http://www.w3.org/Jigsaw/) in order to be able to run Java servlet, and the commandline option gives me an error message ``` Exception in thread "main" java.lang.NoClassDefFoundError: org.w3c.tools.resources.ProtocolException at org.w3c.css.css.CssValidator.main(CssValidator.java:164) ``` How can I validate local CSS on a Linux box?
You can invoke the [W3C validator](http://jigsaw.w3.org/css-validator/DOWNLOAD.html) from the command line: > **Command-Line use** > > Any computer with Java installed can > also run the validator from the > terminal/console as a commandline > tool. Download the css-validator.jar > jar archive (or build it with ant jar) > and run it as : > > `java -jar css-validator.jar http://www.w3.org/` > > Note : the `css-validator.jar` file must > be located at the exact same level as > the lib/ folder to work properly. **Update:** To get it to work, I checked out the full distribution from CVS and ran `ant` using the included `build.xml`. It downloaded all dependencies except for `servlet.jar`. To deal with that, I downloaded the binary distribution of [Tomcat 6](http://tomcat.apache.org/download-60.cgi) and extracted it. Then, I edited the `build.xml` for `css-validator` to reflect the location of `servlet.lib`: ``` <property name="servlet.lib" value="E:/Downloads/apache-tomcat-6.0.20/lib/servlet-api.jar"/> ``` Then ran `ant` again. This produced the `css-validator.jar` file in the top level of the directory checked out from CVS with the `lib` subdirectory containing the other `jar`s it depends on. Then, I was able to run the validator successfully: `C:\Temp\validator\2002\css-validator> java -jar css-validator.jar http://www.unur.com/`
[That jar](http://www.w3.org/QA/Tools/css-validator/css-validator.jar) is runnable, but it needs some extra libraries. Examine the [`MANIFEST.MF`](http://docs.oracle.com/javase/7/docs/technotes/guides/jar/jar.html) file: ``` $ unzip -p css-validator.jar META-INF/MANIFEST.MF Manifest-Version: 1.0 Ant-Version: Apache Ant 1.8.0 Created-By: 1.6.0_26-b03 (Sun Microsystems Inc.) Main-Class: org.w3c.css.css.CssValidator Class-Path: . lib/commons-collections-3.2.1.jar lib/commons-lang-2.6.j ar lib/jigsaw.jar lib/tagsoup-1.2.jar lib/velocity-1.7.jar lib/xerces Impl.jar lib/xml-apis.jar lib/htmlparser-1.3.1.jar ``` You need all the jars mentioned in `Class-Path`. You can download them from the [maven repository](http://mvnrepository.com/) using this script: ``` #!/bin/bash set -e mkdir -p lib curl -LO http://www.w3.org/QA/Tools/css-validator/css-validator.jar echo "\ http://repo1.maven.org/maven2/commons-collections/commons-collections/3.2.1/commons-collections-3.2.1.jar http://repo1.maven.org/maven2/commons-lang/commons-lang/2.6/commons-lang-2.6.jar http://repo1.maven.org/maven2/org/w3c/jigsaw/jigsaw/2.2.6/jigsaw-2.2.6.jar jigsaw.jar http://repo1.maven.org/maven2/org/ccil/cowan/tagsoup/tagsoup/1.2/tagsoup-1.2.jar http://repo1.maven.org/maven2/org/apache/velocity/velocity/1.7/velocity-1.7.jar http://repo1.maven.org/maven2/xerces/xercesImpl/2.11.0/xercesImpl-2.11.0.jar xercesImpl.jar http://repo1.maven.org/maven2/nu/validator/htmlparser/htmlparser/1.2.1/htmlparser-1.2.1.jar\ " | while read url shortname; do if [ -z "$shortname" ]; then shortname="${url##*/}" fi curl -L -o "lib/${shortname}" "${url}" done ``` After doing that, it works: ``` $ java -jar css-validator.jar --output=soap12 file:badcss.html {vextwarning=false, output=soap12, lang=en, warning=2, medium=all, profile=css3} <?xml version='1.0' encoding="utf-8"?> <env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope"> <env:Body> <m:cssvalidationresponse env:encodingStyle="http://www.w3.org/2003/05/soap-encoding" xmlns:m="http://www.w3.org/2005/07/css-validator"> <m:uri>file:badcss.html</m:uri> <m:checkedby>http://jigsaw.w3.org/css-validator/</m:checkedby> <m:csslevel>css3</m:csslevel> <m:date>2013-03-12T06:40:09Z</m:date> <m:validity>false</m:validity> <m:result> <m:errors xml:lang="en"> <m:errorcount>1</m:errorcount> <m:errorlist> <m:uri>file:badcss.html</m:uri> <m:error> <m:line>8</m:line> <m:errortype>parse-error</m:errortype> <m:context> h1 </m:context> <m:errorsubtype> exp </m:errorsubtype> <m:skippedstring> 100% </m:skippedstring> <m:message> Property fnt-size doesn&#39;t exist : </m:message> </m:error> </m:errorlist> </m:errors> <m:warnings xml:lang="en"> <m:warningcount>1</m:warningcount> <m:warninglist> <m:uri>file:badcss.html</m:uri> <m:warning> <m:line>5</m:line> <m:level>0</m:level> <m:message>You should add a &#39;type&#39; attribute with a value of &#39;text/css&#39; to the &#39;style&#39; element</m:message> </m:warning> </m:warninglist> </m:warnings> </m:result> </m:cssvalidationresponse> </env:Body> </env:Envelope> ```
How can I validate CSS on internal web pages?
[ "", "java", "css", "linux", "w3c-validation", "" ]
I've seen this come up here a few times, but in the postings I've seen, no one explained it. Why shouldn't I extend JFrame (or any component)? Are there conditions where I should extend a component, or is this a firm rule that you don't?
Generally speaking, extending the component tends to be done strictly to use the component. This severely limits your options in unnecessary ways in terms of design, so that your classes can't extend different classes, you can't hide the JFrame's methods causing it to be more difficult to maintain and easier to trigger unexpected bugs when using the class. Typically the intention is strictly to use the class to draw a frame, and composition is preferred over inheritance. That being said, subclassing should be fine when you intend your subclass to add project-specific functionality to the Frame (such as convenience methods and the like) where the subclass would be used instead of the Frame itself, but used as a frame in general, not as a view of a specific frame in the application.
Prefer composition over inheritance. All the usual reasons. Composition forces less dependencies between code. Swing, and event AWT, components are hideously complicated. You don't want to be getting into that mess. You can easily override methods accidentally. In cases where you do need to override methods, it's difficult to see where that is done if it is amongst normal code.
Why shouldn't you extend JFrame and other components?
[ "", "java", "swing", "inheritance", "components", "" ]
I want to force my user to only search in a particular folder when using the fileupload control. Is that possible?
No, it's totally up to the client, as long as it's pure HTML, and not, say, ActiveX implementation.
Unfortunately not. The standard web browser file upload control can't be restricted in this way.
FileUpload asp.net
[ "", "c#", "asp.net", "vb.net", "visual-studio-2008", "file-upload", "" ]
I'm currently working on creating a private messaging system, (PHP/MySQL) in which users can send message to multiple recipients at one time, and those users can then decide to reply. Here's what I'm currently working with: ``` tbl_pm tbl: id date_sent title content status ENUM ('unread', 'read') DEFAULT 'unread' tblpm_info tbl: id message_id sender_id receiver_id ``` However, I need some help determining the logic on two things: 1) When a new message is created, should the "id" be auto-increment? If the 'id' column is set to auto-increment in both tables, how would I set the "message\_id" column in the 'relation table'? For example, when a new message is created, my MySQL statement is as follows: ``` <?php mysql_query("INSERT INTO `tblpm` (title, content, sender_id, date_sent) VALUES ('$subject', '$message', '$sender', NOW())" ); ``` In the same statement, how would I enter the 'auto-incremented' value of tblpm into the tblpm\_info "message\_id" field? 2) What should my MySQL statement look like when users reply to messages? Perhaps I am making this more complicated than I need to. Any help is greatly appreciated!
1) Definetely yes, id's should be auto-autoincremented unless you provide a different means of a primary key which is unique. You get the id of the insert either with `mysql_insert_id()` or `LAST_INSERT_ID()` from mysql directly, so to post some connected info you can do either ``` mysql_query("INSERT INTO table1 ...") $foreign_key=mysql_insert_id(); //this gives you the last auto-increment for YOUR connection ``` or, but only if you're absolutely sure no one else writes to the table in the mean time or have control over the transaction, after insert do: ``` $foreign_key=mysql_query("SELECT LAST_INSERT_ID()") INSERT INTO table2 message_id=$foreign_key ``` or, without pulling the FK to php, all in one transaction (I also advice to wrap the SQL as a transaction too) with something like: ``` "INSERT INTO table1...; INSERT INTO table2 (message_id,...) VALUES(LAST_INSERT_ID(),...)" ``` Depending on your language and mysql libraries, you might not be able to issue the multi-query approach, so you're better off with using the first approach. 2) This can have so many approaches, depending on if you need to reply to all the recepients too (e.g. conference), reply in a thread/forum-like manner, whether the client-side can store the last retrieved message/id (e.g. in a cookie; also affecting whether you really need the "read" field). The "private chat" approach is the easiest one, you then are probably better off either storing the message in one table and the from-to relationships into an other (and use JOINs on them), or simply re-populate the message in one table (since storage is cheap nowadays). So, the simplistic model would be one table: ``` table: message_body,from,to $recepients=array(1,2,3..); foreach($recepients as $recepient) mysql_query("INSERT INTO table (...,message_body,from,to) VALUES(...,$from,$recepient)"); ``` (duplicate the message etc, only the recepient changes) or ``` message_table: id,when,message_body to-from-table: id,msg_id,from,to $recepients=array(1,2,3,...); mysql_insert("INSERT INTO message_table (when,message_body) VALUES(NOW(),$body)"); $msg_id=mysql_insert_id(); foreach($recepients as $recepient) mysql_query("INSERT INTO to-from-table (msg_id,from,to) VALUES($msg_id,$from,$recepient)"); ``` (message inserted once, store the relations and FK for all recepients) Each client then stores the last message\_id he/she received (default to 0), and assume all previous messages already read): ``` "SELECT * FROM message WHERE from=$user_id OR to=$user_id WHERE $msg_id>$last_msg_id" ``` or we just take note of the last input time from the user and query any new messages from then on: ``` "SELECT * FROM message WHERE from=$user_id OR to=$user_id WHERE when>='".date('Y-m-d H:i:s',$last_input_time)."' " ``` --- If you need a more conference- or forum-tread-like approach, and need to keep track of who read the message or not, you may need to keep track of all the users involved. Assuming there won't be hundred-something people in one "multi-user conference" I'd go with one table for messages and the "comma-separated and wrapped list" trick I use a lot for storing tags. ``` id autoincrement (again, no need for a separate message id) your usual: sent_at, title (if you need one), content sender (int) recepients (I'd go with varchar or shorter versions of TEXT; whereas TEXT or BLOB gives you unlimited number of users but may have impact on performance) readers (same as above) ``` The secret for recepients/readers field is to populate them comma-separated id list and wrap it in commas again (I'll dulge into why later). So you'd have to collect ids of recepients into an array again, e.g. $recepients=array(2,3,5) and modify your insert: ``` "INSERT INTO table (sent_at,title,content,sender,recepients) VALUES(NOW(),'$title','$content',$sender_id,',".implode(',', $recepients).",')" ``` you get table rows like ... sender | recepients ...          1 | ,2, //single user message ...          1 | ,3,5, //multi user message to select all messages for a user with the id of $user\_id=2 you go with ``` SELECT * FROM table WHERE sender=$user_id OR INSTR(recepients, ',$user_id,') ``` Previously we wrapped the imploded list of recepients, e.g. '5,2,3' becomes ',5,2,3,' and INSTR here tells if ',2,' is contained somewhere as a substring - since seeking for just '2',',2' or '2,' could give you false positives on e.g. '**2**34,56','1\*\*,2**34','9,45**2,\*\*89' accordingly - that's why we had to wrap the list in the first place. When the user reads/receives his/her message, you append their id to the readers list like: ``` UPDATE table SET readers=CONCAT(',',TRIM(TRAILING ',' FROM readers),',$user_id,') WHERE id=${initial message_id here} ``` which results in: ... sender | recepients | readers ...          1 | ,2,              | ,2, ...          1 | ,3,5,           | ,3,5,2, Or we now can modify the initial query adding a column "is\_read" to state whether the user previously read the message or not: ``` SELECT * FROM table WHERE INSTR(recepients, ',$user_id,'),INSTR(readers, ',$user_id,') AS is_read ``` collect the message-ids from the result and update the "recepients" fields with one go ``` "UPDATE table SET readers=CONCAT(',',TRIM(TRAILING ',' FROM readers),',$user_id,') WHERE id IN (".implode(',' ,$received_msg_ids).")" ```
You should not rely on auto-increment on both IDs due to the possibility of two users posting two messages at nearly the same time. If the first script inserts data into the `tbl_pm` table, then the second script manages to execute both its `tbl_pm` and `tblpm_info` inserts before the first script completes its `tblpm_info` insert, the first script's two database inserts will have different IDs. Aside from that, your database structure doesn't seem well organized for the task at hand. Assuming your messages could be very long, and sent to a very large number of users, it would be ideal to have the message content stored once, and for each recipient have unread status, read time, etc. For example: ``` CREATE TABLE `pm_data` ( `id` smallint(5) unsigned NOT NULL auto_increment, `date_sent` timestamp NOT NULL, `title` varchar(255) `sender_id` smallint(5) unsigned, `parent_message_id` smallint(5) unsigned, `content` text, PRIMARY_KEY (`id`) ); CREATE TABLE `pm_info` ( `id` smallint(5) unsigned NOT NULL auto_increment, `pm_id` smallint(5) unsigned NOT NULL, `recipient_id` smallint(5) unsigned, `read` tinyint(1) unsigned default 0, `read_date` timestamp, PRIMARY_KEY (`id`) ); ``` Create these two tables, and notice both of them have an 'id' value set to auto-increment, but the 'info' table also has a `pm_id` field that would hold the ID number of the 'data' row that it refers to, such that you're sure each row has a primary key in the 'info' table that you can use to select from. If you want a true relational database setup using MySQL, make sure your engine is set to InnoDB, which allows relationships to be set up between tables, so (for example) if you try to insert something into the 'info' table that refers to a `pm_id` that doesn't exist in the 'data' table, the INSERT will fail. Once you've chosen a database structure, then your PHP code would look something like: ``` <?php // Store these in variables such that if they change, you don't need to edit all your queries $data_table = 'data_table'; $info_table = 'info_table'; mysql_query("INSERT INTO `$data_table` (title, content, sender_id, date_sent) VALUES ('$subject', '$message', '$sender', NOW())" ); $pmid = mysql_insert_id(); // Get the inserted ID foreach ($recipent_list as $recipient) { mysql_query("INSERT INTO `$info_table` (pm_id, recipient_id) VALUES ('$pmid', '$recipient')" ); } ```
Private Messaging System With Threading/Replies
[ "", "php", "mysql", "insert-id", "" ]
Why does parsing '23:00 PM' with `SimpleDateFormat("hh:mm aa")` return 11 a.m.?
You should be getting an exception, since "23:00 PM" is not a valid string, but Java's date/time facility is [lenient](http://java.sun.com/j2se/1.5.0/docs/api/java/util/Calendar.html#setLenient(boolean)) by default, when handling date parsing. The logic is that 23:00 PM is 12 hours after 11:00 PM, which is 11:00 AM the following day. You'll also see things like "April 31" being parsed as "May 1" (one day after April 30). If you don't want this behavior, set the lenient property to false on your SimpleDateFormat using [DateFormat#setLenient(boolean)](http://java.sun.com/j2se/1.5.0/docs/api/java/text/DateFormat.html#setLenient(boolean)), and you'll get an exception when passing in invalid date/times.
You want "HH:mm aa" as your format, if you will be parsing 24-hour time. ``` public static void main(String[] args) throws ParseException { SimpleDateFormat df = new SimpleDateFormat("HH:mm aa"); final Date date = df.parse("23:00 PM"); System.out.println("date = " + df.format(date)); } ``` outputs ``` date = 23:00 PM ```
Why does parsing '23:00 PM' with SimpleDateFormat("hh:mm aa") return 11 a.m.?
[ "", "java", "datetime", "simpledateformat", "" ]
I'm using C++Test from Parasoft for unit testing C++ code. I came across the following problem. I have a function similar to the next one (pseudocode): ``` bool LoadFileToMem(const std::string& rStrFileName) { if( openfile(rStrFileName) == successfull ) { if( get_file_size() == successfull ) { if( read_entire_file_to_buffer() == successfull ) { return true; } return false; } return false; } return false; } ``` My questions in this case are: Should I use stubs for file system functions? Or should I include specific sample test files for running the unit tests? In my case [std::fstream](http://www.cplusplus.com/reference/iostream/fstream/) class is used for file input. Has anyone better suggestions? (Best if done in C++Test but not mandatory).
For unit-testing THIS function, you should use stubs for each of the called functions. Each called function then has its own unit test suite, which exercises that function. For `read_entire_file_to_buffer()`, you want at least one test file that overflows the buffer, massively, to verify that you do not crash and burn when they feed you the New York Stock Exchange histories instead of the 40-character config file you were expecting.
I would go for short sample test files. They can be checked into source control along with the test code. The reason I would do it is that the intent of your function is to load a file, so this is what you should be testing.
How-to do unit-testing of methods involving file input output?
[ "", "c++", "unit-testing", "file", "stub", "" ]
I'm fairly new to both tools and need to go hardcore with both as I manage, monitor, and tweak a new site's design process. What sort of strategies should I ask be implemented that sets a good solid foundation for debugging, testing, and logging? [to the degree that back-end stuff can play a role - it's .net mvc thx
First off make sure you've read [Firebug's docs](http://getfirebug.com/docs.html). Some of the commands work cross-brower with other tools as well. A simple [search query](https://addons.mozilla.org/en-US/firefox/search?q=firebug&cat=all) will show you all available extensions for Firebug. As some people mentioned - some of them are really helpful. Also it's important not to limit yourself to just a single tool since you will most likely be developing for multiple browsers. So make sure you take a look at webkits developer tools (Safari, Chrome) as well. Here's a [good article](http://www.sitepoint.com/blogs/2008/06/17/in-browser-development-tools-firebug-still-king/) which sums up the most popular development/debug tools. You might want to research how jQuery/jQuery plugins are structured/organized so you have general idea how to organise your own JavaScript/jQuery code. It all depends how JavaScript heavy is your application. If jQuery just provides some visual enhancements and few Ajaxified pages here and there, don't bother. From other hand if it's very JavaScript heavy (as in a lot more site logic on client-side then on backend) I would suggest Prototype over jQuery, but it's just my opinion. You could consider using automatic tools to build your JavaScript if you have a lot of code. For example: * [Sprockets](http://getsprockets.org/) * [Juicer](http://github.com/cjohansen/juicer/tree/master) On production server you want to end up with as few JavaScript files as possible and make sure to compress em. If you're interested in more links to articles/tools for javascript heavy applications, drop a comment. I'm just trying to stay on topic at the moment.
I would use Firebug to see how things are working with a few Firebug Add-ons. I would use [YSlow](https://addons.mozilla.org/en-US/firefox/addon/5369) to check that you aren't downloading too much and it will make suggestions if you aren't minifying and gzipping your javascript. I would also use [FireQuery](http://firequery.binaryage.com/) as that highlights jQuery very nicely in Firebug. I use it quite a lot these days to see what it should be firing. Firebug doesn't rewrite XHRequests anymore but there is a bug in the latest Firefox/Firebug where if can block long running XHR calls. Details [here](https://bugzilla.mozilla.org/show_bug.cgi?id=501962)
What coding conventions that help jQuery and Firebug work together?
[ "", "javascript", "jquery", "asp.net-mvc", "debugging", "firebug", "" ]
Without going into the gory details I want to use a `#define` macro that will expand to a `#include` but the '#' sign is confusing the preprocessor (as it thinks I want to quote an argument.) For example, I want to do something like this: ``` #define MACRO(name) #include "name##foo" ``` And use it thus: ``` MACRO(Test) ``` Which will expand to: ``` #include "Testfoo" ``` The humble # sign is causing the preprocessor to barf. MinGW gives me the following error: `'#' is not followed by a macro parameter` I guess I need to escape the # sign but I don't if this is even possible. Yes, macros are indeed evil...
As far as I remember you cannot use another preprocessor directive in define.
It *is* possible to insert a hash token into the preprocessed token stream. You can do it as follows: ``` #define MACRO(hash, name) hash include name MACRO(#,"hello") ``` —expands to: ``` # include "hello" ``` *However*, the standard explicitly rules out any further analysis of such line for the existence of preprocessing directives [cpp.rescan]: > The resulting completely macro-replaced preprocessing token sequence is not processed as a preprocessing directive even if it resembles one.
Escaping a # symbol in a #define macro?
[ "", "c++", "c", "macros", "c-preprocessor", "preprocessor-directive", "" ]
I have several classes that use the same JNI library, called "jni". In each of those classes, I have a System.loadLibrary() call in the class's static initializer: ``` Class class1 { static{ System.loadLibrary("jni"); } ... } Class class2 { static{ System.loadLibrary("jni"); } ... } ``` The only problem is, I only want System.loadLibrary() to be called once, since it can take a while. Is there an easy and clean way to prevent multiple loadings of the same library?
If the library has already be loaded any subsequent calls to load the same library will be ignored. [`System.loadLibrary`](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/System.html#loadLibrary(java.lang.String)): > Loads the system library specified by > the libname argument. The manner in > which a library name is mapped to the > actual system library is system > dependent. > > The call System.loadLibrary(name) is > effectively equivalent to the call > > ``` > Runtime.getRuntime().loadLibrary(name) > ``` [`Runtime.loadLibrary`](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html#loadLibrary(java.lang.String)): > Loads the dynamic library with the > specified library name. A file > containing native code is loaded from > the local file system from a place > where library files are conventionally > obtained. The details of this process > are implementation-dependent. The > mapping from a library name to a > specific filename is done in a > system-specific manner. > > First, if there is a security manager, > its checkLink method is called with > the libname as its argument. This may > result in a security exception. > > The method System.loadLibrary(String) > is the conventional and convenient > means of invoking this method. If > native methods are to be used in the > implementation of a class, a standard > strategy is to put the native code in > a library file (call it LibFile) and > then to put a static initializer: > > ``` > static { System.loadLibrary("LibFile"); } > ``` > > within the class declaration. When the > class is loaded and initialized, the > necessary native code implementation > for the native methods will then be > loaded as well. > > ***If this method is called more than > once with the same library name, the > second and subsequent calls are > ignored.***
From the [JavaDocs](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html#loadLibrary(java.lang.String)) - > If this method is called more than once with the same library name, the second and subsequent calls are ignored.
Prevent Java from loading library more than once
[ "", "java", "java-native-interface", "" ]
If I have an MS Access database with linked tables from two different database servers (say one table from an SQL Server db and one from an Oracle db) and I write a query which JOINs those two tables, how will Access (or the Jet engine, I guess?) handle this query? Will it issue some SELECTs on each table first to get the fields I'm JOINing on, figurre out which rows match, then issue more SELECTs for those rows?
The key thing to understand is this: Are you asking a question that Access/Jet can optimize before it sends its request to the two server databases? If you're joining the entirety of both tables, Jet will have to request both tables, which would be ugly. If, on the other hand, you can provide criteria that limit one or both sides of the join, Access/Jet can be more efficient and request the filtered resultset instead of the full table.
Yep, you can have some serious performance issues. I have done this type of thing for years. Oracle, Sql, and DB2 - ugh. Sometimes I have had to set it up on a timer at 5:00am so when I get in at 7:00 it's done. If your dataset is significant enough, it is often faster to build a table locally and then link the data. For remote datasets, also look into passthroughs. For example, lets say you are pulling all of yesterday's customers from the oracle db and all of the customer purchases from the sql db. Let's say you have an average of 100 customers daily but a list of 30,000 and lets say your products have a list of 500,000. You could query the oracle db for your list of 100 customers, then write it as in `IN` statement in a passthrough query to the sql db. You'll get your data almost instantly. Or if your recordsets are huge, build local tables of the two IDs, compare them locally and then just pull the necessary matches. It's ugly but you can save yourself hours literally.
Performance of MS Access when JOINing from linked tables in different servers?
[ "", "sql", "performance", "ms-access", "jet", "linked-tables", "" ]
I am using [Eclipse Galileo for Java EE](http://www.eclipse.org/downloads/packages/compare-packages), and I want to configure JUnit to show me the source code when I try to navigate to its methods. I've tried attaching source to the JUnit library, but the library definition is not editable. I cannot even find where to configure the JUnit library in the preferences. When I open the Add Library window and choose JUnit, I see a dialog where I can choose the JUnit version, but it shows that Source Location is "not found". How can I configure Eclipse to find JUnit's source?
I downloaded the Eclipse SDK and checked the differences, and I finally got it to work. 1. Download [this JAR](ftp://ftp.osuosl.org/pub/eclipse/eclipse/updates/3.5/R-3.5-200906111540/plugins/org.junit4.source_4.5.0.v20090423.jar) into your `eclipse/plugins` directory. 2. Edit the file `source.info` in your `eclipse/configuration/org.eclipse.equinox.source` directory, and add the following line: > org.junit4.source,4.5.0.v20090423,plugins/org.junit4.source\_4.5.0.v20090423.jar,-1,false 3. Open the file `artifacts.xml` in your `eclipse` directory, and add the following fragment: ``` <artifact classifier='osgi.bundle' id='org.junit4.source' version='4.5.0.v20090423'> <properties size='2'> <property name='artifact.size' value='128389'/> <property name='download.size' value='128389'/> </properties> </artifact> ``` 4. If Eclipse is already open, you'll need to restart it for the changes to be detected. **Note:** For Eclipse 3.6 (Helios), you should use the updated JAR(s). See the comments by @Supressingfire and @Milo. Note: on Eclipse 3.6(Helios), step 3 (artifacts.xml) is not necessary. Tested on Ubuntu Eclipse 3.6: Version: Helios Service Release 2 Build id: 20110218-0911
As mentioned in [this thread](http://dev.eclipse.org/newslists/news.eclipse.tools.jdt/msg18596.html), if you have downloaded the SDK version of Galileo, you have the sources of the main plugins. For JUnit, this would be: ``` <pathTo>\eclipse-SDK-3.5-win32-x86_64\eclipse\plugins\org.junit4.source_4.5.0.v20090423.jar ``` You can try to add that as a source file in the Source tab of a JUnit launcher configuration and see if that solves your issue when you are debugging your JUnit test and are stepping through JUnit native methods. (Note: I have the x64 version of eclipse Galileo, but I believe the file is the same for the x32 or for other platforms)
How do I configure JUnit's Source in Eclipse?
[ "", "java", "eclipse", "junit", "" ]
Is there any way to put spaces in a C# enum constant? I've read that you can do it in VB by doing this: ``` Public Enum EnumWithSpaces ConstantWithoutSpaces [Constant With Spaces] End Enum ``` ...and then access it like this: ``` Public Sub UsingEnumWithSpaces() Dim foo As EnumWithSpaces = EnumWithSpaces.[Constant With Spaces] End Sub ``` That implies to me that the CLR can handle an enum with spaces. Is there any way to do this in C#?
This blog post might help you: > <http://blog.spontaneouspublicity.com/2008/01/17/associating-strings-with-enums-in-c/> From the article: > But enums can't have spaces in C#!" > you say. Well, I like to use the > System.ComponentModel.DescriptionAttribute > to add a more friendly description to > the enum values. The example enum can > be rewritten like this: ``` public enum States { California, [Description("New Mexico")] NewMexico, [Description("New York")] NewYork, [Description("South Carolina")] SouthCarolina, Tennessee, Washington } ``` Notice that I do not put descriptions on items where the `ToString()` version of that item displays just fine.
CLR can handle absolutely any character in identifiers. However, C# restricts the identifier characters to those legal under the CLS, which space isn't. Same goes for VB.NET, by the way - spaces inside square brackets used to work in VB6, but they don't in VB.NET.
Spaces in C# Enums
[ "", "c#", "vb.net", "enums", "clr", "" ]
I searched google, but coulding find anything. Checked the documentation too... I thought Smarty allowed PHP to be written inside the template itself if you escaped the template engine?
There is the ability to write PHP code inside {php} tags, but you have to turn this on with a smarty config setting. [Smarty PHP Tag](http://smarty.net/manual/en/language.function.php.php)
Note: As of Smarty 3.1 the {php} tags are only available from SmartyBC. Source: <http://www.smarty.net/docs/en/bc.tpl>
Is there a way to use PHP code inside a smarty template?
[ "", "php", "smarty", "" ]
I use jQuery to get the browser version like this: ``` var x = $.browser.version; ``` I get a string like this: **1.9.1.1** Now, I want to do an evaluation so if x is >= 1.9.1 then do some stuff. Unfortunately, with multiple decimal points, I cannot do a parseFloat() because it converts 1.9.1.1 to simply 1.9, and the if evaluation would match a 1.9.0 version (which I do not want). Has someone figured out a way to accomplish turning a version number (with multiple decimals) into something that can be used as a number for evaluation (or some other way to accomplish what I am trying to do here)? Thanks -
You could do something with string.split and then do a digit by digit comparison ``` // arr[0] = 1 // arr[1] = 9 // arr[2] = 1 // arr[3] = 1 var arr = ($.browser.version).split('.'); ``` The following is taken from this [post](http://maymay.net/blog/2008/06/15/ridiculously-simple-javascript-version-string-to-object-parser/) This is a function that will parse your version string and give you back a JSON object ``` function parseVersionString (str) { if (typeof(str) != 'string') { return false; } var x = str.split('.'); // parse from string or default to 0 if can't parse var maj = parseInt(x[0]) || 0; var min = parseInt(x[1]) || 0; var bld = parseInt(x[2]) || 0; var rev = parseInt(x[3]) || 0; return { major: maj, minor: min, build: bld, revision: rev } } ``` Then you could use the following syntax ``` var version = parseVersionString($.browser.version); // version.major == 1 // version.minor == 9 // version.build == 1 // version.revision == 1 ```
Here's another version of `versionCmp()`: ``` function versionCmp(v1, v2) { v1 = String(v1).split('.'); v2 = String(v2).split('.'); var diff = 0; while((v1.length || v2.length) && !diff) diff = (+v1.shift() || 0) - (+v2.shift() || 0); return (diff > 0) - (diff < 0); } ``` Another possibility would be to assign a numeric value to each version number: ``` function valueOfVersion(ver) { ver = String(ver).split('.'); var value = 0; for(var i = ver.length; i--;) value += ver[i] / Math.pow(2, i * 8) || 0; return value; } ``` This only works if each digit is less than 256 (because of the hard-coded divisor) and has a limited precision (ie the version strings can't get arbitrarily long).
How to use Javascript math on a version number
[ "", "javascript", "jquery", "" ]
I'm new to C#, and just started using XmlElement and its SelectSingleNode method. In my XML file there's a tag that may have a value (i.e. `<tag>value</tag>`) or be empty (i.e. `<tag></tag>`). If it's empty, SelectSingleNode returns null. I'm currently using the following code to catch the value of the tag: ``` XmlElement elem = .... string s = elem.SelectSingleNode("somepath").Value; ``` This code obviously raises an exception for empty tags. However, for me an empty tag is a valid value, where I expect the value of my string to be "". Wrapping each call to SelectSingleNode with try...catch seems a huge waste of code (I have many fields that may be empty), and I'm sure there's a better way to achieve this. What is the recommended approach? EDIT: Following requests, a sample XML code will be: ``` <Elements> <Element> <Name>Value</Name> <Type>Value</Type> <-- may be empty <Color>Value</Color> </Element> <Element> <Name>Value</Name> <Type>Value</Type> <Color>Value</Color> </Element> </Elements> ``` The CS code: ``` XmlDocument doc = new XmlDocument(); doc.Load("name.xml"); foreach (XmlElement elem in doc.SelectNodes("Elements/Element")) { myvalue = elem.SelectSingleNode("Type/text()").Value; } ```
Your sample code: ``` myvalue = elem.SelectSingleNode("Type/text()").Value; ``` is where the problem is. The XPath expression you've used there doesn't mean "give me text of element `Type`". It means "give me all child text nodes of element Type". And an empty element doesn't have any child text nodes (a text node cannot be empty in XPath document model). If you want to get text value of the node, you should use: ``` myvalue = elem.SelectSingleNode("Type").InnerText; ```
The recommended approach would be to use .NET's new XML API (namely LINQ to XML). Here is an example: ``` using System; using System.Linq; using System.Xml.Linq; class Program { static void Main() { String xml = @"<Root><Value></Value></Root>"; var elements = XDocument.Parse(xml) .Descendants("Value") .Select(e => e.Value); } } ```
C# XmlElement: SelectSingleNode returns null for empty string?
[ "", "c#", "xml", "" ]
I'm leaving out all the cursor setup and the SELECT from the temp table for brevity. Basically, this code computes a running balance for all transactions per transaction. ``` WHILE @@fetch_status = 0 BEGIN set @balance = @balance+@amount insert into @tblArTran values ( --from artran table @artranid, @trandate, @type, @checkNumber, @refNumber,@custid, @amount, @taxAmount, @balance, @postedflag, @modifieddate ) FETCH NEXT FROM artranCursor into @artranid, @trandate, @type, @checkNumber, @refNumber, @amount, @taxAmount,@postedFlag,@custid, @modifieddate END ``` Inspired by this code from an answer to another question, ``` SELECT @nvcConcatenated = @nvcConcatenated + C.CompanyName + ', ' FROM tblCompany C WHERE C.CompanyID IN (1,2,3) ``` I was wondering if SQL had the ability to sum numbers in the same way it's concatonating strings, if you get my meaning. That is, to create a "running balance" per row, without using a cursor. Is it possible?
You might want to take a look at the update to local variable solution here: [http://geekswithblogs.net/Rhames/archive/2008/10/28/calculating-running-totals-in-sql-server-2005---the-optimal.aspx](https://web.archive.org/web/20200212211219/http://geekswithblogs.net:80/Rhames/archive/2008/10/28/calculating-running-totals-in-sql-server-2005---the-optimal.aspx) ``` DECLARE @SalesTbl TABLE (DayCount smallint, Sales money, RunningTotal money) DECLARE @RunningTotal money SET @RunningTotal = 0 INSERT INTO @SalesTbl SELECT DayCount, Sales, null FROM Sales ORDER BY DayCount UPDATE @SalesTbl SET @RunningTotal = RunningTotal = @RunningTotal + Sales FROM @SalesTbl SELECT * FROM @SalesTbl ``` Outperforms all other methods, but has some doubts about guaranteed row order. Seems to work fine when temp table is indexed though.. * Nested sub-query 9300 ms * Self join 6100 ms * Cursor 400 ms * Update to local variable 140 ms
SQL *can* create running totals without using cursors, but it's one of the few cases where a cursor is actually more performant than a set-based solution (given the operators currently available in SQL Server). Alternatively, a CLR function can sometimes shine well. Itzik Ben-Gan did an excellent series in SQL Server Magazine on running aggregates. The series concluded last month, but you can get access to all of the articles if you have an online subscription. Edit: here's [his latest article in the series](http://www.sqlmag.com/Articles/ArticleID/102097/102097.html?Ad=1) (SQL CLR). Given that you can access the whole series by purchasing an online monthly pass for one month - less than 6 bucks - it's worth your while if you're interested in looking at the problem from all angles. Itzik is a Microsoft MVP and a *very* bright TSQL coder.
How do I calculate a running total in SQL without using a cursor?
[ "", "sql", "sql-server", "" ]
Im new to MVC and I'm re-doing a lot of my code. I have `master.php` (index) which has: ``` <?php require_once("header.php"); ?> ``` Both `master.php` and `header.php` are in the same folder yet I get the following error: > Warning: require\_once(1) [function.require-once]: failed to open stream: No such file or directory in /Users/MyName/Sites/MySite/Views/master.php on line 15 > > Fatal error: require\_once() [function.require]: Failed opening required '1' (include\_path='.:') in /Users/MyName/Sites/MySite/Views/master.php on line 15 This did not happen before. (Files were all in root folder). I don't see what the problem is though, since they are in the same folder - I don't have to go back `'../'` or reference any other folders. What am I missing here? Thanks.
In your comment you say your code is: ``` <?php require_once("header.php") or die; ?> ``` please try leaving out the "or die" -> ist is not necessary, because require\_once will trigger a fatal error if the file is not found. Edit: I tested it, leave out the "or die" and it will work. Edit 2: Explanation why this happened: The above code can also be written like this: ``` require_once ( ("header.php") or die() ); ``` Because require\_once is not a function, but a statement in php, the braces are optional, php interprets the above as a boolean expression, where the string "header.php" gets evaluated to the boolean "true". True gets cast to a string (resulting in "1"), and this string gets passed back to require once. So the above code gets interpreted as ``` require_once("1") ``` Here is how it gets interpreted step by step: ``` (("header.php") or die()) = (TRUE or die()) (TRUE or die()) = TRUE (string) TRUE = '1'; ``` hope this helps ;)
PHP starts looking for 'header.php' in your root folder and can't find it. If it is in the same directory as the current script, you should rather use the magic constant [`__DIR__`](https://www.php.net/manual/en/language.constants.predefined.php): ``` <?php require_once __DIR__ . '/header.php'; ?> ```
require_once problem with templating
[ "", "php", "filesystems", "" ]
I have an old PowerBuilder application that we are slowly phasing out. We are also moving to a more service orientated. So in order to facilitate this we are using C# COM wrappers to call WCF methods so old direct SQL calls can be slowly removed. We also use the C# COM wrappers when need functionality is needed in the power builder application. Since we are using COM calls to DLL from PowerBuilder to C#, there is no need for an external executable. This means that a app.config file will not be loaded on its own. At least that is what I noticed. Example: Let's say the main DLL that has the wrapper methods is Wrapper.dll. If I had config named Wrapper.dll.config it would not get loaded when the make my call from PowerBuilder to C#. The reason I would like to use a config file is because I would like to start using log4net in the C# dlls in order to make debugging easier because it is hard enough with PowerBuilder. There are other reasons that I would like to load configuration files but the easiest to explain is basically it is easier to set up some stuff using a config file. So is there a way to load a configuration files into the Configuration manager for a COM call? Thanks Tony
Thanks for the answers, while helpful it was not what I was looking for. The "easiest" to do what I need is to name the config file after the calling applications exe. So if the application's name is test.exe and your C# dll is wrapper.dll, then you would name the config file test.exe.config. Since test.exe in this case is a PowerBuilder application, I can get away with this for now. If it were a .net app (and probably others) it would probably already have a config and thus get in the way. Tony.
Check out [this code](http://www.koders.com/csharp/fidAD657BD6BAD7B5996A0577D1961430638310A76F.aspx) from [Mike Woodring](http://www.bearcanyon.com/dotnet/). I think it will enable you to do what you want.
Configuration files with COM
[ "", "c#", "com", "configuration", "log4net", "" ]
I am working in a class "A" that requires very high performance and am trying to work out the implications either way. If I inherit this new class "B", the memory profile of "A" should increase by that much. If I include just a ptr to "B" as a member variable in "A", then would I be correct in thinking that, as long as "B" is on the heap (ie new'd up) then "A" will remain as small as it is other than the new ptr reference. Is there something else that I haven't thought of? It is preferable architecture wise for me to inherit "B", however it may be preferable performance wise to just stick with it as a member variable.
I believe inheritance would be the best case here, but every situation is different so here's the pros and cons of each choice. **Inheriting** * Usually requires virtual destructors, this causes a slight overhead during deletion of the object, and increases the size by a 'pointer' (this 1 pointer is used by all virtual objects, so it makes it a lot cleaner) * Allows you to override a function so that it acts correctly for your object even when it is cast to the 'base' class. (Note: This does invoke a small overhead when calling the function) * The size of the class increases by the size of the 'base'. * Any 'base' functions that aren't virtual have NO overhead for calling them. * Generally a lot cleaner (so long as it makes sense to inherit) **Pointing to "base" class** * Requires you to dereference the pointer to the 'base' class everytime you want to call one of its functions (i.e. every 'base' function has overhead) * Impossible to override functions properly (so calling them on the 'base' class invokes the one in the container of the base) without using function pointers (which is possibly more overhead than virtual functions) * Requires separate allocations for both of the allocations, which usually have quite severe performance AND memory implications (allocating is slow, and usually allocations are aligned to a certain boundary, increasing their size, as well as storing extra information so the block can be properly deallocated). * Allows you to NOT allocate the base class, saving memory in that instance * Allows you to change what the 'base' class even after you have created it. Really, I think that as an optimization, this is probably one of the least significant items to investigate. Usually a small change to an algorithm (such as adding in early escapes) will make an astronomical difference compared to this sort of optimization. What should guide this decision is the structure of the program, and on that note, I think **the best advice I can give you is this:** Say, out-loud, the relationship the classes have, if its "Class A ***is*** a Class B" then you should inherit. If you say "Class A ***has*** a Class B" then you should keep a pointer within Class A to Class B.
You are worrying about micro-optimisation. You should first benchmark to determine where your actual bottlenecks are. They will rarely be where you think! They are unlikely to be purely memory based (heap or other wise), and more likely to be algorithm based or constrained by the slowest component in a system (e.g. Disk).
What are the performance implications of inheriting a class vs including a ptr to an instance of the class as a member variable?
[ "", "c++", "" ]
Recently two of our clients have reported problems with our applets. Looking at the java plugin console it is full of ClassNotFoundException so none of our code is executed. I've been able to reproduce the stack trace using a virtual pc image with 0 free space on disk, but the problem goes away as I restore some disk space, and the users tell me that their disk is not full; they are able to create new files. Our applet requires java 6, and the problem has appeared with updates 1, 10 and 14 of the jre. We have also tried different browsers (IE and Firefox), clearing the browser and java caches, ... How can I debug or trace what is the jvm doing to load our applet? I suppose that the problem lies on some security directive on windows so I'm using Sysinternal's Process Monitor to log the activity but I don't really know where to look at.
I've been looking at the plugin source from the JDK and I've found that there is additional debug info available in the logs setting the environment variable `JPI_PLUGIN2_DEBUG`. Unfortunately I still only see `ClassNotFound` exceptions. I've found a piece of the plugin code that swallows all exceptions, so maybe my users problem is there...
The Java cache is most likely messed up. Open Java in the Control Panel and get rid of all temporary files to see if it goes away. Logging in the Java Console for loading applets can be enabled which helps quite alot (even if the plugin is extremely cryptic). See <http://java.sun.com/javase/6/docs/technotes/guides/deployment/deployment-guide/tracing_logging.html>
How to debug/log/trace an applet loading problem?
[ "", "java", "debugging", "logging", "applet", "trace", "" ]
I'm working on a codebase that is known to only run on windows and be compiled under Visual Studio (it integrates tightly with excel so it's not going anywhere). I'm wondering if I should go with the traditional include guards or use `#pragma once` for our code. I would think letting the compiler deal with `#pragma once` will yield faster compiles and is less error prone when copying and pasting. It is also slightly less ugly **`;)`** Note: to get the faster compile times we could use [Redundant Include Guards](http://www.c2.com/cgi/wiki?RedundantIncludeGuards) but that adds a tight coupling between the included file and the including file. Usually it's ok because the guard should be based on the file name and would only change if you needed to change in the include name anyways.
I don't think it will make a significant difference in compile time but `#pragma once` is very well supported across compilers but not actually part of the standard. The preprocessor may be a little faster with it as it is more simple to understand your exact intent. `#pragma once` is less prone to making mistakes and it is less code to type. To speed up compile time more just forward declare instead of including in .h files when you can. I prefer to use `#pragma once`. See this [wikipedia article about the possibility of using both](http://en.wikipedia.org/wiki/Pragma_once).
I just wanted to add to this discussion that I am just compiling on VS and GCC, and used to use include guards. I have now switched to `#pragma once`, and the only reason for me is not performance or portability or standard as I don't really care what is standard as long as VS and GCC support it, and that is that: **`#pragma once` reduces possibilities for bugs.** It is all too easy to copy and paste a header file to another header file, modify it to suit ones needs, and forget to change the name of the include guard. Once both are included, it takes you a while to track down the error, as the error messages aren't necessarily clear.
#pragma once vs include guards?
[ "", "c++", "" ]
This is what I'm trying to do in Python: ``` class BaseClass: def __init__(self): print 'The base class constructor ran!' self.__test = 42 class ChildClass(BaseClass): def __init__(self): print 'The child class constructor ran!' BaseClass.__init__(self) def doSomething(self): print 'Test is: ', self.__test test = ChildClass() test.doSomething() ``` Which results in: ``` AttributeError: ChildClass instance has no attribute '_ChildClass__test' ``` What gives? Why doesn't this work as I expect?
From python documentation: > Private name mangling: When an identifier that textually occurs in a class definition **begins with two or more underscore** characters and does not end in two or more underscores, it is considered a **private name** of that class. Private names are **transformed to a longer form** before code is generated for them. The transformation **inserts the class name in front of the name**, with leading underscores removed, and a single underscore inserted in front of the class name. For example, the identifier **\_\_spam** occurring in a class named **Ham** will be transformed to **\_Ham\_\_spam**. This transformation is independent of the syntactical context in which the identifier is used. If the transformed name is extremely long (longer than 255 characters), implementation defined truncation may happen. If the class name consists only of underscores, no transformation is done. So your attribute is not named **\_\_test** but **\_BaseClass\_\_test**. However you should not depend on that, use **self.\_test** instead and most python developers will know that the attribute is an internal part of the class, not the public interface.
You could use Python's introspection facilities to get you the information you are looking for. A simple dir(test) will give you ``` ['_BaseClass__test', '__doc__', '__init__', '__module__', 'doSomething'] ``` Note the '\_BaseClass\_\_test'. That's what you're looking for. Check [this](http://docs.python.org/tutorial/classes.html) for more information.
Python inheritance and calling parent class constructor
[ "", "python", "oop", "" ]
I have actually no idea of what this is called in C#. But i want to add the functionallity to my class to add multiple items at the same time. ``` myObj.AddItem(mItem).AddItem(mItem2).AddItem(mItem3); ```
The technique you mention is called chainable methods. It is commonly used when creating DSLs or [fluent interfaces](http://en.wikipedia.org/wiki/Fluent_interface) in C#. The typical pattern is to have your AddItem() method return an instance of the class (or interface) it is part of. This allows subsequent calls to be chained to it. ``` public MyCollection AddItem( MyItem item ) { // internal logic... return this; } ``` Some alternatives to method chaining, for adding items to a collection, include: Using the `params` syntax to allow multiple items to be passed to your method as an array. Useful when you want to hide the array creation and provide a variable argument syntax to your methods: ``` public void AddItems( params MyItem[] items ) { foreach( var item in items ) m_innerCollection.Add( item ); } // can be called with any number of arguments... coll.AddItems( first, second, third ); coll.AddItems( first, second, third, fourth, fifth ); ``` Providing an overload of type IEnumerable or IEnumerable so that multiple items can be passed together to your collection class. ``` public void AddItems( IEnumerable<MyClass> items ) { foreach( var item in items ) m_innerCollection.Add( item ); } ``` Use .NET 3.5 collection initializer syntax. You class must provide a single parameter `Add( item )` method, implement IEnumerable, and must have a default constructor (or you must call a specific constructor in the initialization statement). Then you can write: ``` var myColl = new MyCollection { first, second, third, ... }; ```
Use this trick: ``` public class MyClass { private List<MyItem> _Items = new List<MyItem> (); public MyClass AddItem (MyItem item) { // Add the object if (item != null) _Items.Add (item) return this; } } ``` It returns the current instance which will allow you to chain method calls (thus adding multiple objects "at the same time".
Method-Chaining in C#
[ "", "c#", "" ]
I have a template file that contains all my header, footer and common information. It includes the appropriate content for the current page (two-step view pattern). I am trying to set up a login system using PHP Session variables. I can set the variable and sometimes they work but sometimes they disappear. Clicking on links will sometimes make them come back. [My site](http://ejgejg.com/soccer/) Login with username: test password: test There are `var_dumps` of `session_id` and `$_SESSION` at the top. Click on Home. If the session variables disappear click on home (might take as many as 10 times) to see the session information come back. Click on the other navigation and sometimes the session info sticks around and sometimes it doesn't. Here is the session code at the top of my template file. ``` <?php session_start(); require './classes/DBInterface.php'; $db = new DBInterface(); if($_REQUEST['submit'] == 'Login') { $username=$_POST['username']; $password=$_POST['password']; echo '-- login -- '.$username; $rs = $db->verify($username,$password,"admin",0); $admin = $rs->current(); if ($rs->valid()) { $_SESSION['username'] = $username; } } echo ' -- session id -- '; var_dump(session_id()); echo ' -- session var -- '; var_dump($_SESSION); ``` I am using PHP5.
If you are using startlogic (seem you are ?) for your hosting, did you try doing what they say in their FAQ : <http://www.startlogic.com/knowledgebase/read_article.bml?kbid=600> They indicate this : > To run PHP sessions, include the > following code at the top of any PHP > script that uses sessions: > session\_save\_path("your home directory > path"/cgi-bin/tmp); session\_start(); Maybe this'll help ? Especially if they are using some kind of load balancer, which balances /tmp, but not your home directory ?
If you are using a load-balanced setup, it could be that only 1 of the N servers has the correct session-data. By default session-data is stored on the filesystem. Per session a file is stored in /tmp/ and starts with "sess" followed by the session\_id
PHP Session Variables - disappear and reappear
[ "", "php", "" ]
What does result.IsVisible equal? ``` if(a==b) result.IsVisible = obj1.status.abc_REPORT == 'Y' && obj1.AnotherValue.ToBoolean() == false; ```
That depends on the values of `obj1.status.abc_Report` and `obj1.AnotherValue.ToBoolean()` (and it all depends on whether a==b or not). I'm not quite sure of what the real question is here - which bit is confusing you? One bit which *may* be confusing you is the shortcircuiting && operator (and possibly the lack of bracing!) The && operator will *only* evaluate its right hand side if the left hand side evaluates to `true`: and the overall result of the expression is `true` if and only if *both* sides evaluates to `true`. (I'm assuming no strange user-defined conversions here.) So another way of writing it would be: ``` if (a == b) { bool visibility = false; if (obj1.status.abc_REPORT == 'Y') { if (obj1.AnotherValue.ToBoolean() == false) { visibility = true; } } result.IsVisible = visibility; } ``` Note that a condition comparing Booleans, like this: ``` obj1.AnotherValue.ToBoolean() == false ``` would usually be written like this: ``` !obj1.AnotherValue.ToBoolean() ``` (Note the exclamation mark at the start - the logical "not" operator.)
The same as this, in many less lines: ``` if (a==b) { if (obj1.status.abc_REPORT == 'Y') { if (obj1.AnotherValue.ToBoolean() == false) { result.IsVisible = true; } else { result.IsVisible = false; } } else { result.IsVisible = false; } } ```
What does this snippet of C# code do?
[ "", "c#", "" ]
How do I update different columns and rows across a table? I want to do something similiar to [replace a string in SQL server](https://stackoverflow.com/questions/814548/how-to-replace-a-string-in-a-sql-server-table-column) I want to do this but the value exists in multiple columns of the same type. The values are foreign keys varchars to an employee table. Each column represents a task, so the same employee may be assigned to several tasks in a record and those tasks will vary between records. How can I do this effectively? Basically something of a replace all accross varying columns throughout a table. Thanks for any help or advice. Cheers, ~ck in San Diego
This should do the trick: ``` UPDATE table1 SET field1 = replace(field1, 'oldstring', 'newstring'), field2 = replace(field2, 'oldstring2', 'newstring2') ``` etc...
The main idea is to create a SQL Update sentence, no matter how many fields has the table. It was created on SQL Server 2012, however I think it works on 2008 too. Sample table: ``` CREATE TABLE SampleTable ( Field1 INT, Field2 VARCHAR(20), Field3 VARCHAR(20), Field4 VARCHAR(100), Field5 DATETIME, Field6 NVARCHAR(10) ); ``` Get only varchar and nvarchar fields. Change **OLD\_TEXT** and **NEW\_TEXT** accord to your requirement. Change *system\_type\_id* values if you need match not only varchar and nvarchar fields. ``` SELECT 'UPDATE dbo.SampleTable SET ' + STUFF((SELECT ', [' + name + '] = REPLACE([' + name + '], ''OLD_TEXT'', ''NEW_TEXT'')' FROM sys.COLUMNS WHERE [OBJECT_ID] = OBJECT_ID('SampleTable') AND [is_identity] = 0 --It's not identity field AND [system_type_id] in (167, 231) -- varchar, nvarchar FOR XML PATH('')), 1,1, '') ``` The result of the last query is: ``` UPDATE dbo.SampleTable SET [Field2] = REPLACE([Field2], 'OLD_TEXT', 'NEW_TEXT'), [Field3] = REPLACE([Field3], 'OLD_TEXT', 'NEW_TEXT'), [Field4] = REPLACE([Field4], 'OLD_TEXT', 'NEW_TEXT'), [Field6] = REPLACE([Field6], 'OLD_TEXT', 'NEW_TEXT'); ``` just copy the result and execute in SSMS. This snippet saves you a little time when writing the update sentence. Hope it helps.
How can I update multiple columns with a Replace in SQL server?
[ "", "sql", "sql-server", "sql-update", "dynamic-sql", "" ]
How to highlight/select the contents of a DIV tag when the user clicks on the DIV...the idea is that all of the text is highlighted/selected so the user doesn't need to manually highlight the text with the mouse and potentially miss a bit of the text? For example, say we've got a DIV as below: ``` <div id="selectable">http://example.com/page.htm</div> ``` ...and when the user clicks on any of that URL the whole URL text is highlighted so they can easily drag the selected text around in the browser, or copy the complete URL with a right click. Thanks!
``` function selectText(containerid) { if (document.selection) { // IE var range = document.body.createTextRange(); range.moveToElementText(document.getElementById(containerid)); range.select(); } else if (window.getSelection) { var range = document.createRange(); range.selectNode(document.getElementById(containerid)); window.getSelection().removeAllRanges(); window.getSelection().addRange(range); } } ``` ``` <div id="selectable" onclick="selectText('selectable')">http://example.com/page.htm</div> ``` Now you have to pass the ID as an argument, which in this case is "selectable", but it's more global, allowing you to use it anywhere multiple times without using, as chiborg mentioned, jQuery.
## UPDATE 2017: To select the node's contents call: ``` window.getSelection().selectAllChildren( document.getElementById(id) ); ``` This works on all modern browsers including IE9+ (in standards mode). ## Runnable Example: ``` function select(id) { window.getSelection() .selectAllChildren( document.getElementById("target-div") ); } ``` ``` #outer-div { padding: 1rem; background-color: #fff0f0; } #target-div { padding: 1rem; background-color: #f0fff0; } button { margin: 1rem; } ``` ``` <div id="outer-div"> <div id="target-div"> Some content for the <br>Target DIV </div> </div> <button onclick="select(id);">Click to SELECT Contents of #target-div</button> ``` --- The original answer below is obsolete since `window.getSelection().addRange(range);` [has been deprecated](https://www.chromestatus.com/features/6680566019653632) ## Original Answer: All of the examples above use: ``` var range = document.createRange(); range.selectNode( ... ); ``` but the problem with that is that it selects the Node itself including the DIV tag etc. To select the Node's text as per the OP question you need to call instead: ``` range.selectNodeContents( ... ) ``` So the full snippet would be: ``` function selectText( containerid ) { var node = document.getElementById( containerid ); if ( document.selection ) { var range = document.body.createTextRange(); range.moveToElementText( node ); range.select(); } else if ( window.getSelection ) { var range = document.createRange(); range.selectNodeContents( node ); window.getSelection().removeAllRanges(); window.getSelection().addRange( range ); } } ```
Select all DIV text with single mouse click
[ "", "javascript", "css", "" ]
I need a C# function that will take a Byte[] of an 8 bit grayscale TIFF, and return a Byte[] of a 1 bit (black & white) TIFF. I'm fairly new to working with TIFFs, but the general idea is that we need to convert them from grayscale or color to black and white/monochrome/binary image format. We receive the images via a WCF as a Byte[], then we need to make this conversion to black & white in order to send them to a component which does further processing. We do not plan at this point, to ever save them as files. For reference, in our test client, this is how we create the Byte[]: ``` FileStream fs = new FileStream("test1.tif", FileMode.Open, FileAccess.Read); this.image = new byte[fs.Length]; fs.Read(this.image, 0, System.Convert.ToInt32(fs.Length)); fs.Close(); ``` --------update--------- I think there may be more than 1 good answer here, but we ended up using the code from the CodeProject site with the following method added to overload the convert function to accept Byte[] as well as bitmap: ``` public static Byte[] ConvertToBitonal(Byte[] original) { Bitmap bm = new Bitmap(new System.IO.MemoryStream(original, false)); bm = ConvertToBitonal(bm); System.IO.MemoryStream s = new System.IO.MemoryStream(); bm.Save(s, System.Drawing.Imaging.ImageFormat.Tiff); return s.ToArray(); } ```
There is an article on CodeProject [here](http://www.codeproject.com/KB/GDI-plus/BitonalImageConverter.aspx) that describes what you need.
@neodymium has a good answer, but GetPixel/SetPixel will kill performance. [Bob Powell has a great method](https://web.archive.org/web/20140906075741/http://bobpowell.net/onebit.aspx). C#: ``` private Bitmap convertTo1bpp(Bitmap img) { BitmapData bmdo = img.LockBits(new Rectangle(0, 0, img.Width, img.Height), ImageLockMode.ReadOnly, img.PixelFormat); // and the new 1bpp bitmap Bitmap bm = new Bitmap(img.Width, img.Height, PixelFormat.Format1bppIndexed); BitmapData bmdn = bm.LockBits(new Rectangle(0, 0, bm.Width, bm.Height), ImageLockMode.ReadWrite, PixelFormat.Format1bppIndexed); // scan through the pixels Y by X for(int y = 0; y < img.Height; y++) { for(int x = 0; x < img.Width; x++) { // generate the address of the colour pixel int index = y * bmdo.Stride + x * 4; // check its brightness if(Color.FromArgb(Marshal.ReadByte(bmdo.Scan0, index + 2), Marshal.ReadByte(bmdo.Scan0, index + 1), Marshal.ReadByte(bmdo.Scan0, index)).GetBrightness() > 0.5F) { setIndexedPixel(x, y, bmdn, true); // set it if its bright. } } } // tidy up bm.UnlockBits(bmdn); img.UnlockBits(bmdo); return bm; } private void setIndexedPixel(int x, int y, BitmapData bmd, bool pixel) { int index = y * bmd.Stride + (x >> 3); byte p = Marshal.ReadByte(bmd.Scan0, index); byte mask = (byte)(0x80 >> (x & 0x7)); if (pixel) { p |= mask; } else { p &= (byte)(mask ^ 0xFF); } Marshal.WriteByte(bmd.Scan0, index, p); } ```
Need C# function to convert grayscale TIFF to black & white (monochrome/1BPP) TIFF
[ "", "c#", "graphics", "image", "image-processing", "tiff", "" ]
The code is: ``` function roundAmount(theDecimal) { var s = "" + Math.round(theDecimal * 100) / 100 var i = s.indexOf('.') if (i < 0) { return s + ".00" } var t = s.substring(0, i + 1) + s.substring(i + 1, i + 3) if (i + 2 == s.length) t += "0" return t } ``` The line with the error: ``` if (i < 0) return s + ".00" ``` The error is: ``` error: expected (;) ``` does anyone know how to fix this?
**About your script:** The problem in the script above is that last if statement which does some operations followed by a return. You need a semi-colon after the operation. In the future, as good practice, make sure to put a semi-colon after **every** valid statement. That way this won't bother you. Think of each line as a thought, and curly braces as ways to "group" and "relate" thoughts together. The below is a full thought that says "give me a variable "i" and give it the value 1 + 2; ``` var i = 1 + 2; ``` The below is a full thought about a condition that says "If i is 3 then add 1 to i". The thought "add 1 to i" is its own thought, so it needs a semicolon. Since the curlybraces for the IF statement are special in that they don't need a semi-colon after their "full thought" as long as you put a "block" (which is what curlybraces really make) after it, to enclose the thought. This means the following is valid: ``` if( i == 3 ) { i = i + 1; } ``` The following is **not** valid because the semi-colon after the if ends the "thought" before the if knows what to do if i equals 3: ``` if( i == 3 ) ; { i = i + 1; } ``` For a basic JavaScript tutorial, check out [W3Schools](http://www.w3schools.com/js/js_intro.asp "W3C Schools Javascript Tutorial"). **"There must be a better way?"** Any time you find yourself doing a lot of string operations on decmials, it's a good idea to ask yourself "is there a better way to do this?". It looks like you're writing a function to round a number to the nearest hundredths while displaying two decimal points. There's a much easier way to do this. You can just round to the nearest hundredths and have javascript output the fixed point number. Example: ``` function roundAmount( theDecimal ) { //first round to the nearest hundredth //then return the value with two decimal places as a string return theDecimal.toFixed( 2 ); } ```
``` if (i < 0) return s + ".00"; ``` Note the `;` at the end of the statement. Personally, I prefer surrounding almost all my `if`s in `{}` such as ``` if (i < 0) { return s + ".00"; } ``` Which helps in debugging and stepping though code.
How do I fix this syntax error?
[ "", "javascript", "syntax-error", "" ]
The title pretty much says it all. What's the simplest/most elegant way that I can convert, in Java, a string from the format `"THIS_IS_AN_EXAMPLE_STRING"` to the format "`ThisIsAnExampleString`"? I figure there must be at least one way to do it using `String.replaceAll()` and a regex. My initial thoughts are: prepend the string with an underscore (`_`), convert the whole string to lower case, and then use replaceAll to convert every character preceded by an underscore with its uppercase version.
Another option is using Google Guava's `com.google.common.base.CaseFormat` [George Hawkins](https://stackoverflow.com/users/245602/george-hawkins) left a comment with this example of usage: ``` CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, "THIS_IS_AN_EXAMPLE_STRING"); ```
Take a look at [WordUtils in the Apache Commons lang](https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/WordUtils.html) library: Specifically, the capitalizeFully(String str, char[] delimiters) method should do the job: ``` String blah = "LORD_OF_THE_RINGS"; assertEquals("LordOfTheRings", WordUtils.capitalizeFully(blah, '_').replaceAll("_", "")); ``` Green bar!
What is the simplest way to convert a Java string from all caps (words separated by underscores) to CamelCase (no word separators)?
[ "", "java", "regex", "string", "" ]
I have a class Referrals. When you create an object in the class, it checks that the input strings are unique (and therefore never allows duplicate objects). But when I find that input string str1 is equal to that of a previously created object, instead of creating a new object or just returning false, i want to change a property of the already created object. But i can't figure out how to do this, as the method has no way of knowing the name of the object. But I know something unique about it! I feel like this must be enough to *somehow* call it, and do what I need to do. Any ideas? **THANKS!** Here is the class: ``` public class Referral { public class Referral { public string URL; public Dictionary<string, int> Keywords = new Dictionary<string, int>(); private static Dictionary<string, string> URLs = new Dictionary<string, string>(); private int HowManyURLs; private bool UniqueURL; private bool UniqueKeyword; public Referral(string MyURL, string MyKeyword, int MyOccurrences) //Constructor { if (HowManyURLs == 0) { URL = MyURL; Keywords.Add(MyKeyword, MyOccurrences); URLs.Add(MyURL, MyKeyword); HowManyURLs++; } else { // RESET FLAGS UniqueURL = true; UniqueKeyword = true; for ( int i = 0; i < HowManyURLs; i++ ) { if ( URLs.ContainsKey( MyURL ) ) { // TRIP URL FLAG UniqueURL = false; // NOW CHECK KEYWORDS OF URL << THIS IS WHAT I CAN'T DO! if ( URLs.ContainsKey( MyKeyword ) ) { // TRIP KEYWORD FLAG UniqueKeyword = false; // ADD TO OCCURRENCES // Referral[MyURL].Occurrences += MyOccurrences; } } } // IF BOTH FLAGS TRUE if ( UniqueURL == true && UniqueKeyword == true ) { URL = MyURL; Keywords.Add(MyKeyword, MyOccurrences); URLs.Add(MyURL, MyKeyword); HowManyURLs++; } } } } ```
Why don't you create a List of Referral objects *outside* of the Referral object itself? That way you can check the List to see if the object with your criteria already exists. If so, update that object. If not, create a new one and add it to the list. Either that or use a static list, also declared outside of the Referrals class. I'm not 100% sure where you're going with this, so hopefully one of those approaches will work for you.
Try using the [Dictionary.TryGetValue](http://msdn.microsoft.com/en-us/library/bb347013.aspx) method? I didn't quite understand what you're attempting to do with your code, and it's a bit late.
c# call object by unique property
[ "", "c#", "object", "methods", "unique", "call", "" ]
Google is failing me (or I am failing Google.) I am simply looking for the function that executes an INSERT statement using the mysql.h library in C++.
Not too familiar with using MySQL in C, but according to what I can see in the [mysql.h](http://leithal.cool-tools.co.uk/sourcedoc/mysql509/html/mysql_8h.html) file, you should call mysql\_stmt\_prepare to create the statement, and mysql\_stmt\_execute to execute said prepared statement.
Have you tried [MySQL++](http://dev.mysql.com/doc/refman/5.0/en/apis-cplusplus.html)? <http://tangentsoft.net/mysql++/>
How do you execute an INSERT statement using MySQL (in c++)?
[ "", "c++", "mysql", "linux", "" ]
Is there any way to have multi-line plain-text, constant literals in C++, à la Perl? Maybe some parsing trick with `#include`ing a file? I know you can do it with raw strings in C++11.
Well ... Sort of. The easiest is to just use the fact that adjacent string literals are concatenated by the compiler: ``` const char *text = "This text is pretty long, but will be " "concatenated into just a single string. " "The disadvantage is that you have to quote " "each part, and newlines must be literal as " "usual."; ``` The indentation doesn't matter, since it's not inside the quotes. You can also do this, as long as you take care to escape the embedded newline. Failure to do so, like my first answer did, will not compile: ``` const char *text2 = "Here, on the other hand, I've gone crazy \ and really let the literal span several lines, \ without bothering with quoting each line's \ content. This works, but you can't indent."; ``` Again, note those backslashes at the end of each line, they must be immediately before the line ends, they are escaping the newline in the source, so that everything acts as if the newline wasn't there. You don't get newlines in the string at the locations where you had backslashes. With this form, you obviously can't indent the text since the indentation would then become part of the string, garbling it with random spaces.
In C++11 you have raw string literals. Sort of like here-text in shells and script languages like Python and Perl and Ruby. ``` const char * vogon_poem = R"V0G0N( O freddled gruntbuggly thy micturations are to me As plured gabbleblochits on a lurgid bee. Groop, I implore thee my foonting turlingdromes. And hooptiously drangle me with crinkly bindlewurdles, Or I will rend thee in the gobberwarts with my blurlecruncheon, see if I don't. (by Prostetnic Vogon Jeltz; see p. 56/57) )V0G0N"; ``` All the spaces and indentation and the newlines in the string are preserved. These can also be utf-8|16|32 or wchar\_t (with the usual prefixes). I should point out that the escape sequence, V0G0N, is not actually needed here. Its presence would allow putting )" inside the string. In other words, I could have put ``` "(by Prostetnic Vogon Jeltz; see p. 56/57)" ``` (note extra quotes) and the string above would still be correct. Otherwise I could just as well have used ``` const char * vogon_poem = R"( ... )"; ``` The parens just inside the quotes are still needed.
How to write a multi-line string literal
[ "", "c++", "string-literals", "rawstring", "" ]
I am attempting to scroll the window to a location on my page based on a user's selection. I am getting some strange results. Can anyone suggest a good/better way to go about this? Here is what I'm working with: ``` var rel = $(this).attr('rel'); var citation = rel.split("-")[0]; window.scrollTo(0, $('[name = ' + citation + ' ]').offset().top); alert($('[name = ' + citation + ' ]').offset().top); ``` The last alert gives me a number that seems wrong and the scrolling is not working. The following code is executed when the user clicks on a link from within the document. I am capturing that element's rel attribute value and (after a little string manipulation) using it to find the position of the corresponding anchor. The destination element's name attribute should match the rel attribute of the clicked link. See what I mean? Thanks!
I was able to get around this by not using offset() but by rather using jQuery's position() function. I am just getting the returned object's "top" property. I have to use the element's text as an index value because these elements did not have unique IDs. ``` var citationIndex = parseInt($(this).text() - 1); var elementOffset = $('.HwCitationsContent li:eq(' + citationIndex + ')').position().top; ```
This is another easy oldschool way to scroll to a html element: ``` // scrolls to the element with id='citation' var node = document.getElementById('citation'); node.scrollIntoView(); ```
Getting anchor's offset position
[ "", "javascript", "jquery", "scroll", "" ]
I am working on some rather inefficient C# code that wants to remove blanks lines. It does this: ``` string b; ... while ( b.IndexOf("\n\n") >= 0 ) b = b.Replace ("\n\n", "\n"); ``` A single replace would not cope with (e.g.) \n\n\n in the input, so the loop is needed. I think it ought to work, and it usually does. But sometimes it manages to get into an infinite loop, and I don't understand how. On every iteration the number of \n should reduce, so it ought to terminate eventually. Any ideas?
Would this work: ``` String c = Regex.Replace(b, "\n\n+", "\n"); ```
I don't have an explanation for your inexplicable infinite loop (are you CERTAIN it's infinite? Have you checked to see if the string changes?), but you can do this much easier and faster with a regular expression: ``` b = System.Text.RegularExpressions.Regex.Replace(b, "\n+", "\n") ```
How can Replace infinite loop?
[ "", "c#", "string", "replace", "infinite-loop", "" ]
I have a problem that I can't figure out myself. I've tried using LEFT JOIN etc but nothing seems to work. I'm using MySQL so you know. I'm building a little blogportal for me and my friends and all users have their own blog. database: **users:** id, username, password, etc **blog:** id, title, text, user\_id, etc **relations** follower\_id, following\_id I query my own blogposts like this: ``` SELECT * FROM microblog WHERE user_id = {$user_id} ORDER BY posted DESC ``` and i list my friends like this: ``` SELECT * FROM users, relations WHERE relations.follower_id = {$user_id} AND relations.following_id = users.id ``` That was the easy part. BUT. I rather JOIN the tables somehow because I also want to list my friends blogposts inside my loop. But I don't just want the post to show, I also want some info about the user that posted that one so then I must get some info from the users table as well. And that's what bothers me! I can't figure it out. In short: I want to list my own blog posts and all the users I'm friend with within my own loop. And I also want to display username and email beside the posts. Hope you understand what I mean. /Tobias Sweden
How about? ``` select u.username, u.email, m.title, m.text -- ... etc from microblog m inner join user u on m.user_id = u.id where m.user_id = {$user_id} or m.user_id in (select following_id from relations r where follower_id = {$user_id} ); ```
Try this? ``` SELECT m.* FROM microblog m INNER JOIN users u ON m.user_id = u.user_id LEFT JOIN relations r ON r.following_id = m.user_id WHERE m.user_id = {$user_id} OR (r.follower_id = {$user_id} AND NOT IsNull(r.follower_id)) ORDER BY posted DESC ```
Get results from my own and "friends" posts
[ "", "php", "mysql", "join", "" ]
When you have a model field with a choices option you tend to have some magic values associated with human readable names. Is there in Django a convenient way to set these fields by the human readable name instead of the value? Consider this model: ``` class Thing(models.Model): PRIORITIES = ( (0, 'Low'), (1, 'Normal'), (2, 'High'), ) priority = models.IntegerField(default=0, choices=PRIORITIES) ``` At some point we have a Thing instance and we want to set its priority. Obviously you could do, ``` thing.priority = 1 ``` But that forces you to memorize the Value-Name mapping of PRIORITIES. This doesn't work: ``` thing.priority = 'Normal' # Throws ValueError on .save() ``` Currently I have this silly workaround: ``` thing.priority = dict((key,value) for (value,key) in Thing.PRIORITIES)['Normal'] ``` but that's clunky. Given how common this scenario could be I was wondering if anyone had a better solution. Is there some field method for setting fields by choice name which I totally overlooked?
Do as [seen here](http://www.b-list.org/weblog/2007/nov/02/handle-choices-right-way/). Then you can use a word that represents the proper integer. Like so: ``` LOW = 0 NORMAL = 1 HIGH = 2 STATUS_CHOICES = ( (LOW, 'Low'), (NORMAL, 'Normal'), (HIGH, 'High'), ) ``` Then they are still integers in the DB. Usage would be `thing.priority = Thing.NORMAL`
As of Django 3.0, you can use: ``` class ThingPriority(models.IntegerChoices): LOW = 0, 'Low' NORMAL = 1, 'Normal' HIGH = 2, 'High' class Thing(models.Model): priority = models.IntegerField(default=ThingPriority.LOW, choices=ThingPriority.choices) # then in your code thing = get_my_thing() thing.priority = ThingPriority.HIGH ```
Set Django IntegerField by choices=... name
[ "", "python", "django", "django-models", "" ]
I want to write a function that outputs something to a `ostream` that's passed in, and return the stream, like this: ``` std::ostream& MyPrint(int val, std::ostream* out) { *out << val; return *out; } int main(int argc, char** argv){ std::cout << "Value: " << MyPrint(12, &std::cout) << std::endl; return 0; } ``` It would be convenient to print the value like this and embed the function call in the output operator chain, like I did in `main()`. It doesn't work, however, and prints this: ``` $ ./a.out 12Value: 0x6013a8 ``` The desired output would be this: ``` Value: 12 ``` How can I fix this? Do I have to define an `operator<<` instead? **UPDATE:** Clarified what the desired output would be. **UPDATE2:** Some people didn't understand why I would print a number like that, using a function instead of printing it directly. This is a simplified example, and in reality the function prints a complex object rather than an `int`.
You can't fix the function. Nothing in the spec requires a compiler to evaluate a function call in an expression in any particular order with respect to some unrelated operator in the same expression. So without changing the calling code, you can't make `MyPrint()` evaluate after `std::cout << "Value: "` Left-to-right order is mandated for expressions consisting of multiple consecutive << operators, so that will work. The point of operator<< returning the stream is that when operators are chained, the LHS of each one is supplied by the evaluation of the operator to its left. You can't achieve the same thing with free function calls because they don't have a LHS. `MyPrint()` returns an object equal to `std::cout`, and so does `std::cout << "Value: "`, so you're effectively doing `std::cout << std::cout`, which is printing that hex value. Since the desired output is: ``` Value: 12 ``` the "right" thing to do is indeed to override operator<<. This frequently means you need to either make it a friend, or do this: ``` class WhateverItIsYouReallyWantToPrint { public: void print(ostream &out) const { // do whatever } }; ostream &operator<<(ostream &out, const WhateverItIsYouReallyWantToPrint &obj) { obj.print(out); } ``` If overriding `operator<<` for your class isn't appropriate, for example because there are multiple formats that you might want to print, and you want to write a different function for each one, then you should either give up on the idea of operator chaining and just call the function, or else write multiple classes that take your object as a constructor parameter, each with different operator overloads.
You want to make MyPrint a class with friend operator<<: ``` class MyPrint { public: MyPrint(int val) : val_(val) {} friend std::ostream& operator<<(std::ostream& os, const MyPrint& mp) { os << mp.val_; return os; } private: int val_; }; int main(int argc, char** argv) { std::cout << "Value: " << MyPrint(12) << std::endl; return 0; } ``` This method requires you to insert the MyPrint object into the stream of your choice. If you REALLY need the ability to change which stream is active, you can do this: ``` class MyPrint { public: MyPrint(int val, std::ostream& os) : val_(val), os_(os) {} friend std::ostream& operator<<(std::ostream& dummy, const MyPrint& mp) { mp.os_ << mp.val_; return os_; } private: int val_; std::ostream& os_ }; int main(int argc, char** argv) { std::cout << "Value: " << MyPrint(12, std::cout) << std::endl; return 0; } ```
Function that prints something to std::ostream and returns std::ostream?
[ "", "c++", "outputstream", "ostream", "" ]
I have been happy serializing with javascript objects into JSON using ``` JSON.stringify ``` And sending along to my "static" webmethod in c#/asp.net and sure enought it arrives .. I need the correct number of parameters hence if my json object has "startDate","endDate","reserve" then my webmethod needs these as parameters. "Basically with my order object that i have, i have a number of parameters on this object so i would need to use the same number on the webmethod - this is a bit messy??" - I will explain I have a rather complex "Order" object in javascript and wish to serialize it using stringify and send it along to my webmethod but i don't want to specify all the parameters is there a way round this? I was hoping for something like this on my webmethod ``` public static bool MakeReservation(object order) ``` Then in my webmethod i only have 1 parameter BUT i can then desearilize this to a true c# object using JSON.NET. I have tried it like this sending the json across but because there is ONLY 1 parameter on my webmethod its failing. Basically what i am trying to say if i that i want to continue to use my webmethod but i don't want to have to do specify 15 parameters on the webmethod I want the JSON - String to arrive into my webmethod and then i can decompose it on the server. Is this possible? Here is how i am currently sending my JSON to the server (webmethod) using jquery ``` var jsonData = JSONNew.stringify(orderObject); $.ajax({ type: "POST", url: "MyService.aspx/DoReservation", data: jsonData, contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { success = true; }, error: function(msg) { success = false; }, async: false }); ```
If you try to submit an object that looks like this: ``` JSON.stringify({ endDate: new Date(2009, 10, 10), startDate: new Date() }); ``` it will try and map endDate and startDate to corresponding parameters in your webmethod. Since you only want to accept one single method, I suspect you may get away with it by submitting the following: ``` JSON.stringify({ order: orderObject }); ``` Which it might reasonably try to assign as a value to the 'order' parameter of your webmethod. Failing that, submitting ``` JSON.stringify({ order: JSON.stringify(orderObject) }); ``` and then deserializing it using JSON.NET should definitely work, but it's uglier, so try the first example first. That's my best shot.
It's possible. I'm not so good at explaining stuff, I'll just show you my example code: Javascript: ``` var Order = function(name, orderid, price) { this.name = name; this.orderid = orderid; this.price = price;} var pagePath = window.location.pathname; function setOrder() { var jsOrder = new Order("Smith", 32, 150); var jsonText = JSON.stringify({ order: jsOrder }); $.ajax({ type: "POST", url: pagePath + "/SetOrder", contentType: "application/json; charset=utf-8", data: jsonText, dataType: "json", success: function(response) { alert("wohoo"); }, error: function(msg) { alert(msg); } }); } ``` C# Code behind ``` public class Order { public string name { get; set; } public int orderid { get; set; } public int price { get; set; } } [WebMethod] public static void SetOrder(object order) { Order ord = GetOrder(order); Console.WriteLine(ord.name +","+ord.price+","+ord.orderid); } public static Order GetOrder(object order) { Order ord = new Order(); Dictionary<string,object> tmp = (Dictionary<string,object>) order; object name = null; object price = null; object orderid = null; tmp.TryGetValue("name", out name); tmp.TryGetValue("price", out price); tmp.TryGetValue("orderid", out orderid); ord.name = name.ToString(); ord.price = (int)price; ord.orderid = (int) orderid; return ord; } ``` My code isn't that beautiful but I hope you get the meaning of it.
Passing complex JSON string to 1 parameter webmethod in c# - desearialize into object (json.net)?
[ "", "c#", "jquery", "web-services", "asmx", "json.net", "" ]
Storing an array submitted from forms stores elements with null values. Is there a way to store only non null fields into the php array? $\_SESSION['items'] = $\_POST['items']; is my current code.
You should take a look at [array\_filter()](https://www.php.net/manual/en/function.array-filter.php). I think it is exactly what you are looking for. ``` $_SESSION['items'] = array_filter($_POST['items']); ```
``` # Cycle through each item in our array foreach ($_POST['items'] as $key => $value) { # If the item is NOT empty if (!empty($value)) # Add our item into our SESSION array $_SESSION['items'][$key] = $value; } ```
html form arrays how to store into php array not including null elements
[ "", "php", "html", "" ]
I've already read the MSDN article about it. It seems internally it is the way c# sets which is the function that is going to work as indexer(am I right?). Now, I've seen the following example: ``` [DefaultMemberAttribute("Main")] public class Program { public static void Main() { ... } } ``` Now, I don't get it what it means. --- Thanks all. But I still can't get its usefulness, apart from the indexer thing. When are we going to call InvokeMember?
I personally have never used it, but as far as I can tell you are defining the default method to be invoked when calling [InvokeMember](http://msdn.microsoft.com/en-us/library/system.type.invokemember.aspx). So, using the code snippet you provided if I was to say: ``` Program prog = new Program(); typeof(Program).InvokeMember("", null, null, prog, null); ``` Because I left the first argument empty of the InvokeMember call it would use the attribute to determine what the default member is of your class, in your case it is Main.
No, the [`DefaultMemberAttribute`](http://msdn.microsoft.com/en-us/library/system.reflection.defaultmemberattribute.aspx) is used by languages such as VB.NET to find out the member that is acted on by default if no member is referenced from an object, i.e. the member invoked by [`InvokeMember`](http://msdn.microsoft.com/en-us/library/system.type.invokemember.aspx). This is often used in conjunction with indexers, as you noted, but it is not used by C# directly (unless you use [`InvokeMember`](http://msdn.microsoft.com/en-us/library/system.type.invokemember.aspx) explicitly). However, for the benefit of other .NET languages, C# does emit the [`DefaultMemberAttribute`](http://msdn.microsoft.com/en-us/library/system.reflection.defaultmemberattribute.aspx) for the indexer of a class (if it has one), as indicated by [MSDN](http://msdn.microsoft.com/en-us/library/system.reflection.defaultmemberattribute.aspx): > The C# compiler emits the > DefaultMemberAttribute on any type > containing an indexer. In C# it is an > error to manually attribute a type > with the DefaultMemberAttribute if the > type also declares an indexer. I think MSDN confuses things by referring to indexers a lot in the remarks but then giving an example that does not use an indexer. To clarify, the default member can be anything, but C# gives special behavior for indexers by emitting the attribute for you (if an indexer exists) to the exception of all other use cases.
DefaultMemberAttribute - what does it do?
[ "", "c#", ".net", "vb.net", "attributes", "" ]
I’m looking for a bit of feedback on the practice of requesting users to authenticate to an intranet based web app by entering their AD credentials directly in form fields. For example, using domain\username and password fields as opposed to using the native browser based challenge window for integrated authentication. In the form based example, credentials are passed to the application in plain text and it’s essentially up to the integrity of the application to handle the data appropriately. It seems to me this is the equivalent of entering my Open ID credentials directly into a host app on the Internet. So my questions are: 1. Is there any best practice guidance on authenticating to a custom web app (assume predominantly .NET / Java stacks) in an AD environment? 2. Can you think of any legitimate circumstances where this is really necessary? 3. Is this a legitimate concern or am I just being paranoid?!
In a highly secure environment, users would be encouraged to only enter their credentials when using the *Secure Attention Sequence* CTRL-ALT-DEL, which is designed so that it can't be intercepted by applications. So in such an environment, even the browser challenge window for authentication would be suspect. Instead you would log on locally using the same AD credentials as you need to access the website, and would be authenticated without needing to be prompted. I'd say entering AD credentials in form fields is extremely suspect if the credentials can also be used for access to other sensitive resources. Even if the app developers are well-intentioned, it is an unnecessary security hole. For example, anyone who has write access to the web directory can easily replace the login form and capture credentials.
If it's a browser based application, why wouldn't you just enable Windows authentication in your web.config (not sure what the equivalent is in the Java world, sorry) and let the browser handle authentication. Otherwise, I'd say if you do this over a secure transport (SSL) then you should be ok. Microsoft's own products often use form fields to submit AD credentials (I know Outlook Web Access and Internet Security & Acceleration Server both do this).
Is using AD credentials entered into form fields as opposed to the browser integrated auth window bad practice?
[ "", "java", ".net", "security", "active-directory", "" ]
I have a really, really nasty bit of JS code that I've inherited. The code is quite long, and quite obtrusive. The functions defined are all about a thousand or so lines each... Anyway, since there isn't a call to anything as elegant as onload, I am trying to figure out how what is on the screen gets on the screen. Thus I need a way to separate the fly crap from the pepper as it were... I need to be able to find the code that is not contained in functions and is just called "out in the wild" so I can find out where this silly program begins...does anybody know a good way to do this?
A brute-force method could be to include some script at the very top (of the script includes) to set the document object to undefined/null so that any references to its methods will cause a runtime error. That may help you spot the line # and filename of the first bit of code that tries to get something on the screen.
Firefox & Firebug -- set breakpoints and step through the code as it executes. The other thing you could do is start refactoring into classes/objects and see what breaks in the console (due to no references). I'd probably take a run through the debugger first, though.
How to find the Javascript that is not contained in a function?
[ "", "javascript", "" ]
I have a JSF converter that I use for a SelectItem list containing several different entity types. In the `getAsString()` method I create the string as the class name suffixed with ":" and the ID. ``` MySuperClass superClass = (MySuperClass)value; if(superClass != null) { return String.valueOf(superClass.getClass().getName()+":"+superClass.getId()); } ``` This allows me to load the correct entity in the `getAsObject()` on the way back from the UI by doing this : ``` String className = value.substring(0, value.indexOf(":")); long id = Long.parseLong(value.substring(value.indexOf(":")+1)); Class<T> entitySuperClass = (Class<T>) Class.forName(className); MySuperClass superClass = (MySuperClass)getEntityManager().find(entitySuperClass, id); ``` My problem is that my entity in `getAsString()` is a proxy. So instead of getting `com.company.MyEntity` when I do a getClass().getName() I am getting `com.company.MyEntity_$$_javassist_48` so then it fails on the `find()`. Is there any way (aside from String manipulation) to get the concrete class name (eg. com.company.MyEntity)? Thanks.
Instead of `superClass.getClass()` try `org.hibernate.proxy.HibernateProxyHelper.getClassWithoutInitializingProxy(superClass)`.
There is one important difference between **Hibernate.getClass()** and **HibernateProxyHelper**! The **HibernateProxyHelper** always returns the superclass that represents the table in the database if you have and entity that is mapped using ``` @Table(name = SuperClass.TABLE_NAME) @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = SuperClass.TABLE_DISCRIMINATOR, discriminatorType = DiscriminatorType.STRING) ``` and ``` @DiscriminatorValue(value = EntityClass.TABLE_DISCRIMINATOR) ``` in the subclass. **Hibernate.getClass(...)** returns the real subclass for those.
Loading javassist-ed Hibernate entity
[ "", "java", "hibernate", "jpa", "" ]
The documentation specifies how to add inline attachement, but what is the correct way of referencing it from the html part? Is it possible to include images automatically as it is in other libraries? Maybe someone has written a little snippet and is willing to share?
That's not exactly a trivial thing, lucky for you someone has subclassed Zend\_Mail (`Demo_Zend_Mail_InlineImages`) to do that, see here: <http://davidnussio.wordpress.com/2008/09/21/inline-images-into-html-email-with-zend-framework/>
i write wrapper for mail class ``` private function _processHtmlBody($I_html, $I_mailer, $I_data) { $html = $I_html; $mail = $I_mailer; $xmlBody = new DomDocument(); $xmlBody->loadHTML($html); $imgs = $xmlBody->getElementsByTagName('img'); $I_data['atts'] = array(); $imgCount = 0; foreach ($imgs as $img) { $imgCount++; $imgUrlRel = $img->getAttribute('src'); $imgId = sha1(time() . $imgCount . $imgUrlRel); $html = str_replace($imgUrlRel, 'cid:' . $imgId, $html); $imgUrlFull = 'http://' . $_SERVER['HTTP_HOST'] . $imgUrlRel; $imgBinary = file_get_contents($imgUrlFull); $imgPart = $mail->createAttachment($imgBinary); $imgPart->filename = 'image' . $imgCount . '.jpg'; $imgPart->id = $imgId; $I_data['atts'][] = $imgPart; } $mail->setBodyHtml($html); return $html; } ```
How to send an email with inline images using zend framework?
[ "", "php", "zend-framework", "email", "inline-images", "" ]
I have a page that calls another page(on another server) and I want that page to read the title from the parent page. Is this possible or is there some security issue with this?
You cannot communicate across servers like that.
You can use JavaScript to access the parent: ``` window.parent.document.title ```
How can I read the page title of the parent page from an iframe?
[ "", "javascript", "xss", "" ]
Is there a way to make [`Throwable.printStackTrace(PrintStream s)`](http://java.sun.com/javase/6/docs/api/java/lang/Throwable.html#printStackTrace%28java.io.PrintStream%29) print the full stack trace, so that I can see beyond the final line of `"... 40 more"`?
You don't need to; that information is present elsewhere in the stack trace. From the docs of [`printStackTrace()`](http://docs.oracle.com/javase/8/docs/api/java/lang/Throwable.html#printStackTrace--): > Note the presence of lines containing the characters `"..."`. These lines indicate that the remainder of the stack trace for this exception matches the indicated number of frames from the bottom of the stack trace of the exception that was caused by this exception (the "enclosing" exception). > > This shorthand can greatly reduce the length of the output in the common case where a wrapped exception is thrown from same method as the "causative exception" is caught. In other words, the `"... x more"` only appears on a chained exception, and only when the last `x` lines of the stack trace are already present as part of another chained exception's stack trace. Suppose that a method catches exception Foo, wraps it in exception Bar, and throws Bar. Then Foo's stack trace will be shortened. If you for some reason want the full trace, all you need to do is take the last line before the `...` in Foo's stack trace and look for it in the Bar's stack trace; everything below that line is exactly what would have been printed in Foo's stack trace.
Let's take the stack trace from the documentation of [Throwable.printStackTrace()](https://docs.oracle.com/javase/8/docs/api/java/lang/Throwable.html#printStackTrace--): ``` HighLevelException: MidLevelException: LowLevelException at Junk.a(Junk.java:13) at Junk.main(Junk.java:4) Caused by: MidLevelException: LowLevelException at Junk.c(Junk.java:23) at Junk.b(Junk.java:17) at Junk.a(Junk.java:11) ... 1 more Caused by: LowLevelException at Junk.e(Junk.java:30) at Junk.d(Junk.java:27) at Junk.c(Junk.java:21) ... 3 more ``` The causes are displayed from the most nested one at the bottom (the "root cause"), to the one which the printed stack trace belongs to. In this case the root cause is `LowLevelException`, which caused `MidLevelException`, which caused `HighLevelException`. To get the complete stack trace you have to look at the frames of the enclosing exception (and its enclosing exceptions): 1. Look at how many frames were omitted: "... **X** more" 2. Look for the omitted frames at the enclosing exception 1. Look at how many frames were omitted: "... **Y** more" 2. Append the first X - Y frames to the stack trace 3. If Y > 0, repeat step 2 with it as number of omitted frames So if we wanted to get the complete stack trace of `LowLevelException` we would do the following: 1. Look at how many frames were omitted: "... **3** more" 2. Look for the omitted frames at the enclosing exception (`MidLevelException`) 1. 1 frame has been omitted ("... **1** more") 2. Append the first 2 (3 - 1) frames to the stack trace 3. Repeat step 2 with 1 as number of omitted frames 1. Look at the enclosing exception of `MidLevelException` (`HighLevelException`) 2. Append the first 1 frame to the stack trace Your complete stack trace then looks like this: ``` LowLevelException at Junk.e(Junk.java:30) at Junk.d(Junk.java:27) at Junk.c(Junk.java:21) // From MidLevelException stack trace at Junk.b(Junk.java:17) at Junk.a(Junk.java:11) // From HighLevelException stack trace at Junk.main(Junk.java:4) ``` --- Side notes: * There might be cases where no frames are listed, e.g.: ``` HighLevelException: MidLevelException at Junk.main(Junk.java:4) Caused by: MidLevelException ... 1 more ``` This can happen when the cause it created in the same line: `new HighLevelException(new MidLevelException())`. Don't get confused by this, the approach described above still works, there are just no frames to use from the exception, continue with its enclosing one. * In some cases you can save yourself the counting by looking at the first frame which was not omitted (the line above `... X more`). If you know which methods call the method in that line you can directly search for the callers in the frames of the enclosing exception: ``` HighLevelException: MidLevelException: LowLevelException at Junk.c(Junk.java:29) at Junk.b(Junk.java:21) at Junk.a(Junk.java:13) at Junk.main(Junk.java:4) Caused by: MidLevelException // You know Junk.d is only called by Junk.b at Junk.d(Junk.java:35) ... 3 more ```
How do I increase the number of displayed lines of a Java stack trace dump?
[ "", "java", "exception", "" ]
There is a Java paradigm for database access implemented in the Java `DataSource`. This object create a useful abstraction around the creation of database connections. The `DataSource` object keeps database configuration, but will only create database connections on request. This is allows you to keep all database configuration and initialization code in one place, and makes it easy to change database implementation, or use a mock database for testing. I currently working on a Python project which uses cx\_Oracle. In cx\_Oracle, one gets a connection directly from the module: ``` import cx_Oracle as dbapi connection = dbapi.connect(connection_string) # At this point I am assuming that a real connection has been made to the database. # Is this true? ``` I am trying to find a parallel to the `DataSource` in cx\_Oracle. I can easily create this by creating a new class and wrapping cx\_Oracle, but I was wondering if this is the right way to do it in Python.
You'll find relevant information of how to access databases in Python by looking at [PEP-249: Python Database API Specification v2.0](http://www.python.org/dev/peps/pep-0249/). `cx_Oracle` conforms to this specification, as do many database drivers for Python. In this specification a `Connection` object represents a database connection, but there is no built-in pooling. Tools such as [SQLAlchemy](http://www.sqlalchemy.org/) do provide pooling facilities, and although SQLAlchemy is often billed as an ORM, it does not have to be used as such and offers nice abstractions for use on top of SQL engines. If you do want to do object-relational-mapping, then SQLAlchemy does the business, and you can consider either its own declarative syntax or another layer such as [Elixir](http://elixir.ematia.de/) which sits on top of SQLAlchemy and provides increased ease of use for more common use cases.
I don't think there is a "right" way to do this in Python, except maybe to go one step further and use another layer between yourself and the database. Depending on the reason for wanting to use the DataSource concept (which I've only ever come across in Java), SQLAlchemy (or something similar) might solve the problems for you, without you having to write something from scratch. If that doesn't fit the bill, writing your own wrapper sounds like a reasonable solution.
cx_Oracle and the data source paradigm
[ "", "python", "database", "oracle", "cx-oracle", "" ]
Occasionally I find I need to process a list by inserting a new item after each item, except the last one. Similar to how you might put a comma between each item of a list of strings. I got fed up of coding the special case for the last (or first) item every time, so I captured the pattern in a Linq-style extension: ``` public static IEnumerable<T> Separate<T>(this IEnumerable<T> source, Func<T> separator) { bool first = true; foreach (T item in source) { if (first) first = false; else yield return separator(); yield return item; } } ``` For example, this allows me to easily programatically fill a flow document with hyperlinks, but with a line-break between each one: ``` para.Inlines.AddRange(_recentFiles.Select(f => f.ToHyperlink()) .Separate(() => new LineBreak())); ``` Assuming this doesn't already exist in System.Linq.Enumerable (which is what I typically discover immediately after writing something like this), the question is, what is this `Separate` operation on lists usually called in other functional frameworks or languages?
Haskell: [`intersperse`](http://www.zvon.org/other/haskell/Outputlist/intersperse_f.html) `Zip` usually means a different operation (`zip [a, b, c] [x, y, z] = [(a, x), (b, y), (c, z)]`)
It's often called Join.
In functional list manipulation, what do we call "inserting something between each item"?
[ "", "c#", "language-agnostic", "functional-programming", "stream", "lazy-evaluation", "" ]
example: ``` class Vendor_ClassName_Helper { CONST FIRST_OPTION = 1; CONST SECOND_OPTION = 2; public function __construct($option, $otherArgument) { } } ``` client code: ``` $obj = new Vendor_ClassName_Helper(Vendor_ClassName_Helper::FIRST_OPTION, $var); ``` Any good ways to avoid the long lines (and this is a rather short example)? Maybe other ways to implement the same?
I think clarity is better than short code. You can try to think of different words of expressing the same or different form. For your example, it doesn't seem very bad as Omega pointed out, and his method of splitting declaration on multiple lines is good as well. Here's another trick: Depending on what your option constants do, you may want to employ a factory method instead of the new-keyword. For example, ``` class Example { private function __construct() { } public static method createA(..) { //configure for mode A $cls = new self; return $cls; } public static method createB(..) { //configure for mode B $cls = new self; return $cls; } } $x = Example::createA(); ```
I avoid long lines and improve readability in most languages by breaking up the parameters into their own kind of block... ``` $obj = new Vendor_ClassName_Helper( Vendor_ClassName_Helper::FIRST_OPTION, $var ); ``` But two options doesn't always warrant it in my opinion. Static constants unfortunately can't really be changed and you do of course want them to remain descriptive. What you have here isn't so bad :)
avoiding long class constants as parameters - PHP
[ "", "php", "oop", "coding-style", "" ]
a report in my application runs a query that needs between 5 - 15 seconds (constrained to count of rows that will be returned). The query has 8 joins to nearly all main-tables of my application (Customers, sales, units etc). A little tool shows me, that in this time, all those 8 tables are locked with a shared table lock. That means, no update operation will be done in this time. A solution from a friend is, to have every join in the query, which is not mandetory to have 100% correct data (dirty read), with a NoLock, so only 1 of this 8 tables will be locked completly. Is that a good solution? For a report in which 99% of data came from one table, unlock the less prio tables?
Try looking at READ COMMITTED SNAPSHOT rather than NOLOCK. This means the data could be "old" but will never be dirty.
`NOLOCK` means placing no locks at all. Your query may returns portions of data as of before `UPDATE` and portions as of after `UPDATE` *in a single query*. Like, a debit without a credit and these kinds of stuff. For instance, I just ran this query on a large table: ``` SELECT SUM(LEN(name)) FROM master WITH (NOLOCK) OPTION (MAXDOP 1) --- 18874367 ``` All `name`'s have length of `1`. Then I reran it and in the middle of the query updated the table: ``` UPDATE master SET name = 'tt' WHERE id <= 10000 SELECT SUM(LEN(name)) FROM master WITH (NOLOCK) OPTION (MAXDOP 1) --- 18874944 ``` As we can see, this query noticed `577` rows as updated (length `2`), all other rows as not updated (length `1`). ``` SELECT SUM(LEN(name)) FROM master WITH (NOLOCK) OPTION (MAXDOP 1) --- 18884367 ``` And this query, run right after the previous one finished, sees all updates.
SQL Server Table locks in long query - Solution: NoLock?
[ "", "sql", "sql-server", "" ]
when validating methods' input, I used to check if the argument is null, and if so I throw an ArgumentNullException. I do this for each and every argument in the list so I end up with code like this: ``` public User CreateUser(string userName, string password, string Email, string emailAlerts, string channelDescription) { if (string.IsNullOrEmpty(userName)) throw new ArgumentNullException("Username can't be null"); if (string.IsNullOrEmpty(Email)) throw new ArgumentNullException("Email can't be null"); //etc, etc, etc } ``` Is this OK? Why should I do this? Would it be ok if I simply group all the checks and return a null value instead of throwing the exception? What is the best practice to address this situation? **PS:** I want to change this, because with long methods, it gets very tedious to do so. Ideas?
Make an ArgChecker class with something like this ``` ArgChecker.ThrowOnStringNullOrEmpty(userName, "Username"); ``` where ThrowOnStringNullOrEmpty is ``` public static void ThrowOnStringNullOrEmpty(string arg, string name) { if (string.IsNullOrEmpty(arg)) throw new ArgumentNullException(name + " can't be null"); } ``` You could also try to process a list of arguments using a params arg, like: ``` public static void ThrowOnAnyStringNullOrEmpty(params string[] argAndNames) { for (int i = 0; i < argAndName.Length; i+=2) { ThrowOnStringNullOrEmpty(argAndNames[i], argAndNames[i+1]); } } ``` and call like this ``` ArgChecker.ThrowOnAnyStringNullOrEmpty(userName, "Username", Email, "email"); ```
An approach which I use and I may have picked up from the NHibernate source is to create a static class `Guard`, used as follows: ``` public void Foo(object arg1, string arg2, int arg3) { Guard.ArgumentNotNull(arg1, "arg1"); Guard.ArgumentNotNullOrEmpty(arg2, "arg2"); Guard.ArgumentGreaterThan(arg3, "arg3", 0); //etc. } public static class Guard { public static void ArgumentNotNull(object argument, string parameterName) { if (parameterName == null) throw new ArgumentNullException("parameterName"); if (argument == null) throw new ArgumentNullException(parameterName); } //etc. } ``` This cuts down a lot of the chaff at the beginning of methods and it performs well.
What is the best practice in case one argument is null?
[ "", "c#", ".net", "argument-validation", "" ]
What is the proper way to use `**kwargs` in Python when it comes to default values? `kwargs` returns a dictionary, but what is the best way to set default values, or is there one? Should I just access it as a dictionary? Use `get` function? ``` class ExampleClass: def __init__(self, **kwargs): self.val = kwargs['val'] self.val2 = kwargs.get('val2') ``` People do it different ways in code that I've seen and it's hard to know what to use.
You can pass a default value to `get()` for keys that are not in the dictionary: ``` self.val2 = kwargs.get('val2',"default value") ``` However, if you plan on using a particular argument with a particular default value, why not use named arguments in the first place? ``` def __init__(self, val2="default value", **kwargs): ```
While most answers are saying that, e.g., ``` def f(**kwargs): foo = kwargs.pop('foo') bar = kwargs.pop('bar') ...etc... ``` is "the same as" ``` def f(foo=None, bar=None, **kwargs): ...etc... ``` this is not true. In the latter case, `f` can be called as `f(23, 42)`, while the former case accepts named arguments **only** -- no positional calls. Often you want to allow the caller maximum flexibility and therefore the second form, as most answers assert, is preferable: but that is not always the case. When you accept many optional parameters of which typically only a few are passed, it may be an excellent idea (avoiding accidents and unreadable code at your call sites!) to force the use of named arguments -- `threading.Thread` is an example. The first form is how you implement that in Python 2. The idiom is so important that in Python 3 it now has special supporting syntax: every argument after a single `*` in the `def` signature is keyword-only, that is, cannot be passed as a positional argument, but only as a named one. So in Python 3 you could code the above as: ``` def f(*, foo=None, bar=None, **kwargs): ...etc... ``` Indeed, in Python 3 you can even have keyword-only arguments that *aren't* optional (ones without a default value). However, Python 2 still has long years of productive life ahead, so it's better to **not** forget the techniques and idioms that let you implement in Python 2 important design ideas that are directly supported in the language in Python 3!
Proper way to use **kwargs in Python
[ "", "python", "default-value", "keyword-argument", "" ]
I'm working on the address page for a shopping cart. There are 2 `<select>` boxes, one for Country, one for Region. There are 6 standard countries available, or else the user has to select "Other Country". The `<option>` elements all have a numeric value - Other Country is 241. What I need to do is hide the Region `<select>` if the user selects Other Country, and also display a textarea.
You need to bind a function to the select list so that when it changes, your function decides if the div should be shown. Something like this (~~untested, hopefully syntactically close~~). **Here's a [live example](http://jsbin.com/uhozu)**. ``` $(document).ready( function() { $('#YourSelectList').bind('change', function (e) { if( $('#YourSelectList').val() == 241) { $('#OtherDiv').show(); } else{ $('#OtherDiv').hide(); } }); }); ```
It's the same principle as [this question](https://stackoverflow.com/questions/1100066/filter-table-from-select-input-using-jquery). You just need to connect to the change on the select , check the `val()` and `hide()/show()` the div.
jQuery: Showing a div if a specific a <select> option is selected?
[ "", "javascript", "jquery", "forms", "select", "" ]
I'm new to MVC. You have been warned... I have User model that can return a MySQL result resource to a controller. The controller passes the MySQL resource over to the view to display. Is it acceptable to print the query results in the view, using a database result fetching function? ``` <?php while($row = some_fetching_function($database_result_resource): ?> <tr> <td><?=$row['Username']?></td> ...etc </tr> <?php endwhile; ?> ``` That doesn't look right to me. It's tightly coupled, right? The model must return some type of database resource, and the view has to loop through it using some type of database fetching method. Can that be decoupled without looping through the results twice? I'm thinking you would have to loop through the results in the model to create an array of the results, and then again in the view. In summary: 1. Can the view display a database result resource, while adhering to the MVC design pattern? 2. Is it possible to avoid looping through the data twice, while avoiding tight coupling to a database?
If you abstract away the database part of the code I think it's acceptable. For example, you could provide a "rowset" which can be iterated (implement Iterable interface or something). Behind the scenes, this object could contain a database result and use the fetching function. Basically the idea is that your view deals with a generic looking rowset which doesn't imply it's coming from a database or any other source, and that way you reduce the coupling.
Of course it can. But you actually shouldn't fetch the rows in your view. Do the Assignment of model data in your controller, but not directly in the view. As Hooray Im Helping pointed out, the fetching of data depends on the Model you are using. But you shouldn't have any Database specific methods or model logic in your view. If model implements a generic [Iterator](https://www.php.net/manual/en/class.iterator.php) interface you could pass it directly to the view. ``` <?php public function someControllerAction($params) { $myModel = Model::getModel('Model Name'); // But you don't do Model::getModel('Model Name')->getResults($params['date']) in your viewa $this->view->rows = $myModel->getResults($params['date']); } ?> ```
MVC: Can a view loop through query results?
[ "", "php", "database", "model-view-controller", "" ]
Theres some reason for this code not reach the first else? I got it exactly the same from vairous sources. Than I did my own encapsulation. Everything goes fine. Window is created, messages are treated, events are generated to keyborad input in the client area, the gl canvas works fine (when I force it to draw). The only problem is that message loop never leaves the first if. :/ I'm really stuck. ``` while (!done) { if (::PeekMessage (&msg, NULL, 0, 0, PM_REMOVE)) { if (msg.message == WM_QUIT) { done = TRUE; } else { ::TranslateMessage (&msg); ::DispatchMessage (&msg); } } else { // Code is never reaching this! draw (); ::SwapBuffers(hDC); idle (); } } return msg.wParam; ```
In your case the message queue must never be empty - why? Well it depends on what the rest of your program is doing. Some possibilities: 1. Your code is posting new messages to the queue in a manner such that the queue doesn't get empty. I'd suggest logging out the message ids as they are handled. 2. You aren't handling paint messages - from msdn: "The PeekMessage function normally does not remove WM\_PAINT messages from the queue. WM\_PAINT messages remain in the queue until they are processed. However, if a WM\_PAINT message has a NULL update region, PeekMessage does remove it from the queue." Hope this helps. [Edit] To handle WM\_PAINT either call BeginPaint and EndPaint or forward to DefWindowProc
Make sure you are processing the **WM\_PAINT** correctly. By this I mean make sure you are calling **BeginPaint** and **EndPaint** from inside the **WM\_PAINT** message, otherwise you will be confusing *Windows* into thinking your application still needs to be painted.
Windows message loop
[ "", "c++", "winapi", "opengl", "" ]
This seems like a stupid question, but I'm tripping over it at the moment. Why does this compile? ``` import java.util.*; public class Test { public static void main (String[] argv) throws Exception { Map<String,String> map = new HashMap<String,String>(); map.get(new ArrayList<String>()); } } ``` Shouldn't it be illegal to call get with something that's not compatible with "String"?
See [this](https://stackoverflow.com/questions/1045721/java-6-map-get-type-safety-unexpected-behavior/1045758#1045758) Also [this](https://stackoverflow.com/questions/857420/what-are-the-reasons-why-map-getobject-key-is-not-fully-generic)
From the Javadocs for [Map](http://java.sun.com/javase/6/docs/api/java/util/Map.html "Map"): ``` V get(Object key) ``` > Returns the value to which the > specified key is mapped, or null if > this map contains no mapping for the > key. get is simply a method which takes in ANY object, and will (if it exists) return an object that was mapped to it. So passing it a non-string is legal, however, since all the keys have to be strings, you'll always get null if you pass in a non-string.
Why does this code with generics compile?
[ "", "java", "generics", "" ]
I am getting different message digests from the linux 'sha512sum' tool and the python hashlib library. Here is what I get on my Ubuntu 8.10: ``` $ echo test | sha512sum 0e3e75234abc68f4378a86b3f4b32a198ba301845b0cd6e50106e874345700cc6663a86c1ea125dc5e92be17c98f9a0f85ca9d5f595db2012f7cc3571945c123 - $ python Python 2.5.2 (r252:60911, Oct 5 2008, 19:24:49) [GCC 4.3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import hashlib >>> hashlib.sha512("test").hexdigest() 'ee26b0dd4af7e749aa1a8ee3c10ae9923f618980772e473f8819a5d4940e0db27ac185f8a0e1d5f84f88bc887fd67b143732c304cc5fa9ad8e6f57f50028a8ff' ``` Both should calculate the message digest of the string "test", why do you think I am getting different results?
I think the difference is that echo adds a newline character to its output. Try echo -n test | sha512sum
`echo` is adding a newline: ``` $ python -c 'import hashlib; print hashlib.sha512("test\n").hexdigest()' 0e3e75234abc68f4378a86b3f4b32a198ba301845b0cd6e50106e874345700cc6663a86c1ea125dc5e92be17c98f9a0f85ca9d5f595db2012f7cc3571945c123 ``` To avoid that, use `echo -n`.
Difference in SHA512 between python hashlib and sha512sum tool
[ "", "python", "digest", "sha512", "hashlib", "" ]
The BBC just released their JavaScript library, [Glow](http://www.bbc.co.uk/glow/docs/articles/what_is_glow.shtml). They rolled their own because the major libraries don't adequately support older browsers. I'm wondering if I should take the time to learn the library. Do other large institutions have similar laws and rules regulating them that prevent them from using the mainstream libraries such as jQuery?
The BBC's primary duty is not to make money, instead, it is to serve the license-payer. In order to reach the widest possible audience, they have to support those older browsers. There's a large number of people in this world who couldn't be bothered—or don't even know how—to upgrade their web browsers from IE 5.old or whatever they're using now. The BBC can't just say "well too bad for you" to these people, even though private broadcasters can. (Disclaimer: I'm from the US so this is mostly conjecture based on what I've learned about the BBC from other sources, e.g. Wikipedia. Please correct me in the comments if I'm wrong, or downvote me mercilessly. Either works.)
[Browser stats](http://www.w3schools.com/browsers/browsers_stats.asp) suggest it would be a waste of time. From my own relatively high-traffic public-facing website, older browsers (generation 1 firefox, netscape 5 or less, MSIE 5 or less) last month registered 40,000 hits out of 8.3 million, or 0.5%. It also seems to me that any organization restricting you to some ancient browser might be the same ones that restrict you from browsing the BBC. None of the companies I deal with at work have restrictions for older browsers either, and we have a couple hundred clients ranging from small to fortune 500. Thank goodness too - I can't imagine trying to make our application work for older browsers.
Marginal browser support by the BBC (and why the BBC they can't use jQuery)
[ "", "javascript", "jquery", "bbc-glow", "" ]
I have a website where the login info is optionally saved in a cookie (remember me checkbox at login) and when the user logs out, the value of the authentication cookie won't change to expire the cookie allowing logout. The system does work correctly in both the dev and staging servers but for some reason will not work on our production server. We are running PHP 5 and Apache on all the servers. Thanks. Function to set cookie (minor edits for security): ``` function setCookieInfo($data,$expiry=0) { if($data === false) { //remove cookie! $cookie = false; $expiry = 100; //should be in the past enough! } else { $serial = base64_encode(serialize($data)); $hash = md5($XXX); $cookie = $hash."---".$serial; } if($_SERVER['SERVER_NAME']=='localhost') { $domain = null; } else { $domain = '.'.$_SERVER['SERVER_NAME']; } return setcookie('Auth', $cookie, $expiry, $this->controller->base, $domain); } ```
Posting some actual code might help, but I'll hazard a guess that it has something to do with the cookie domain being used.
Assuming you are using the PHP setcookie() function, make sure that the domain and path for the cookie are set correctly. Check [PHP's documentation](http://us.php.net/setcookie) for the function for more information. I might be able to tell you for sure if I had a little more info. Can you provide any more information without compromising too much about the project? How about the URLs of the dev, staging, and production servers, or at least examples of what they might be like? **Edit** Based upon the info you provided in your comment, I would recommend that you try using HTTP\_HOST instead of SERVER\_NAME. SERVER\_NAME might be giving you a weird value depending upon your virtual server setup. Your path might not be quite right either - try a '/' and it should be available regardless of the subdirectory the user is in. Also, ``` $this->controller->base ``` makes me think that you might be using CodeIgniter or Kohana. If so, you might consider using their cookie helpers.
Why won't my cookie value change in PHP 5?
[ "", "php", "cookies", "" ]
I'm working on a storefront application in PHP with MySQL. I'm currently storing my data in 4 tables: one for product lines, one for specific products within those product lines, one for product images, and one which specifies which images are linked to which specific products. Each specific product belongs to one product line, each product image can belong to several specific products, and each specific product can have several images. My tables look like this: ``` ProductLines id, name, description, etc. SpecificProducts productLineID id, color, size, etc. ProductImageLinks specificProductID imageID Images id, imageFileLocation, name, etc. ``` It's working fine this way, but it seems like it's not very efficient for retrieval purposes. For example, I have a page that lists each product line along with a thumbnail of a randomly chosen image from that product line. To do that I have to first query the database for a list of all product lines, then perform a separate query for *each product line* to get all of the specific products that have associated images, pick one of those, and then query again to get the image. Another possibility I considered would be to use one query to get all the product lines I'm looking at, a second query to get all the specific products for all of those product lines, a third query to get all of the image links which specify which images are linked to which specific products, and a fourth query to get all those images. I imagine this would be a bit faster because of the reduced number of queries, but it would leave a lot of work for PHP to do figuring out the connections between product lines and products and images, which could be just as slow. So my question is, is there a better way to store this data? Or a better way to retrieve it based on the database I already have in place? Or is one of the two options I've identified really my best bet? Edit: I'm not actually storing image files in the database. The image files are stored in the file system. My "Images" table in the database just stores the location of the image file along with useful info like the image title, alt text, etc.
Yes - just write a single query that will retrieve all that information in one shot. I'm a little rusty on this, but you can lookup the queries in mysql reference. 1. create a query that joins these tables on the appropriate keys 2. you need to select the first item from a subquery that retrieves the images for a specific query, and then order by rand() and select the first. This can definitely be done in a single query. Even if it can't you can always create views which is sometimes a better way to organize your queries so that they are more readable. In other words, instead of returning the result of your query, just create a view corresponding to your first query. Then create a view that corresponds to running your second query on the result of the first query, that operates off the view. And so on. Then, your actually query can be done in one shot by retrieving from the final view.
As far the database design goes, you have a fairly solid (and standard) design. You could combine your ProductImageLinks and Images tables as long as it's a 1:1 relationship to save some queries. As for your product line image retrieval, you have a couple of options that would drastically reduce the number of queries required: 1. Create a new table in your database called ProductLineImages. Instead of picking the image randomly from the associated products, load a set of images in there that you can choose randomly from. It won't be as dynamic this way, but this is the most efficient method. 2. You can do all of what you described in a single (but less efficient than #1) query.
How should I store product and product image data for an online store?
[ "", "php", "mysql", "database-design", "" ]
how do I prevent slow loading external js files from blocking the loading process of the whole website (because the browser processes 2 requests only at a time)? Let's say I want to include the sharethis button but the server is encountering heavy load and needs to long to serve my request, how can I force the rest to load anyway. Or should I add the external scripts after the site has loaded already? I'm using RoR with jQuery. Best, Ole
Personally I would load the extra items after the ones that you need. For example add the code to bottom of the page so that jQuery has already loaded and then load them from jQuery like below ``` $(document).ready(function(){ $.getScript("urlofscript"); }); ``` Details of getScript() [here](http://docs.jquery.com/Ajax/jQuery.getScript)
You should dinamycally load the external JavaScripts by using `$(document).ready()` function of jQuery. You'll have to create the `<script>` elements and append them to your document.
How to prevent external JS to block your site from loading?
[ "", "javascript", "jquery", "ruby-on-rails", "performance", "" ]
I ponder this question from time to time, so I thought I'd ask you guys about it. Let's say I have a database table that looks like this: ``` Table: Visibility Id Value -- ----- 0 Visible 1 Invisible 2 Collapsed ``` This is just a table for ensuring referential integrity. It is basically an enum stored in the database for the purposes of ensuring that any Visiblity values that appear in other tables are always valid. Over in my front end, I have some choices. 1. I could query this table and store it in, say, a `Dictionary<string, int>` or a `Dictionary<int, string>`. 2. I could write an enum by hand and just manually edit the values in the rare event that there is a change to the table. E.g., `public enum Visiblity { Visible, Invisible, Collapsed }` 3. Something else???? Which would you advise and why? Thanks.
For fairly trivial stuff like this, I usually go with an enum. I can identify with you in the sense that I feel it's not completely right... but in my opinion it's the lesser of two evils. Some additional justification for this: if for some reason a fourth value were to be added, your code would need updating anyway to be able to be able to handle that. While you're at it, it's very little trouble to also update the enum.
In the event that you need to add a new value to the table will this require a coding change in your application to support that new value? If so, make it an `enum`.
Syncing referential integrity tables and enums
[ "", "c#", "database", "enums", "referential-integrity", "" ]
Note: Currently using Perforce as a CM tool. I currently do several debug releases of software [only debug files (.pdb) and binaries (.dll and .exe)]. At every release, I check the all the files used to generate the binaries into our CM tool (baseline). Then I checkout the files and continue making changes. Currently, if there was an issue with one of the releases such that we needed to debug it, I would have to revert the code back to the version used. My question is, how should I go about easily debugging old versions? If I create a branch from the baseline I just did, then I could easily just build the previous version for debugging, but what about further back than that? I don’t want to branch every time I do a baseline (pretty sure I don’t want to do that). I know with VHDL you can create builds with test points and use the Xilinx tools to debug any built version of VHDL. Is there a similar way we can do this in VS (maybe using the .pdb files and some external tools)? How do you go about baselining revisions so that you can easily debug old version?
Eric Sinc has a fantasic [Source Control HOWTO](http://www.ericsink.com/scm/source_control.html) that covers this topic (and much more). I would highly recommend reading it because this guy knows his stuff. You'd be most interested in [Chapter 6: History](http://www.ericsink.com/scm/scm_history.html) and [Chapter 7: Branches](http://www.ericsink.com/scm/scm_branches.html). This stuff really helped me when I was learning about source control and software release strategies.
With p4 you don't have to create a branch to go "back in time". All you have to do is sync to the appropriate tag or change number. For instance, if you were to recreate version 1.1 of ProductX, and the last change in p4 was change number 2000, you can do the following: ``` p4 sync //depot/ProductX/...@2000 ``` or if a tag was used, such as "Release1.1" you can do this: ``` p4 sync //depot/ProductX/...@Release1.1 ``` or if you couldn't figure those out, you could even try to sync at a certain date. Such as: ``` p4 sync //depot/ProductX/...@2009/02/01:12:15:00 ``` For more information in p4 concerning file revisions, try this: ``` p4 help revisions ```
How to debug old versions of software?
[ "", "c#", "debugging", "version-control", "configuration-management", "" ]
I've got an application, written in C++, that uses boost::asio. It listens for requests on a socket, and for each request does some CPU-bound work (e.g. no disk or network i/o), and then responds with a response. This application will run on a multi-core system, so I plan to have (at least) 1 thread per core, to process requests in parallel. Whats the best approach here? Things to think about: * I'll need a fixed size thread pool (e.g. 1 thread per CPU) * If more requests arrive than I have threads then they'll need to be queued (maybe in the o/s sockets layer?) Currently the server is single threaded: * It waits for a client request * Once it receives a request, it performs the work, and writes the response back, then starts waiting for the next request Update: More specifically: what mechanism should I use to ensure that if the server is busy that incoming requests get queued up? What mechanism should I use to distribute incoming requests among the N threads (1 per core)?
I don't see that there is much to consider that you haven't already covered. If it is truly CPU-bound then adding threads beyond the number of cores doesn't help you much *except* if you are going to have a lot of requests. In that case the listen queue may or may not meet your needs and it might be better to have some threads to accept the connections and queue them up yourself. Checkout the listen backlog values for your system and experiment a bit with the number of threads. UPDATE: listen() has a second parameter that is your requested OS/TCP queue depth. You can set it up to the OS limit. Beyond that you need to play with the system knobs. On my current system it is 128 so it is not huge but not trivial either. Check your system and consider whether you realistically need something larger than the default. Beyond that there are several directions you can go. Consider KISS - no complexity before it is actually needed. Start off with something simple like just have a thread to accept connection (up to some limit) and plop them in a queue. Worker threads pick them up, process, write result, and close socket. At the current pace of my distro's Boost updates (and my lack of will to compile it myself) it will be 2012 before I play with ASIO - so I can't help with that.
ACE <http://www.cs.wustl.edu/~schmidt/ACE/book1/> It has everything you need. Thread management and queues and as an added bonus a portable way of writing Socket Servers.
I have a server listening on sockets, whats a good approach to service CPU-bound requests with multiple threads?
[ "", "c++", "multithreading", "sockets", "boost-asio", "" ]
in my project if compile project in release, it asks me MSVCP90.dll. if it is debug, it does not... have you ever met such a situation? and do you know why this .dll is desired? or what configuration makes it to be desired? thanks for any advice..
i realized that i already installed Microsoft Visual C++ 2008 Redistributable Package so i just repaired but it did not solved the problem. then i looked for the configuration and saw that "Generate Manifest" is "No" in Release when it was "Yes" in Debug. so i changed and tried again then it worked. i did not know that this configuration may affect like that, (and i dont remember when i changed it) anyway.. thanks for your other answers...
I think you need to install Microsoft Visual C++ 2008 Redistributable Package which you can get from [here](http://www.microsoft.com/downloads/details.aspx?FamilyID=9b2da534-3e03-4391-8a4d-074b9f2bc1bf&displaylang=en).
MSVCP90.dll not found?
[ "", "c++", "visual-studio", "configuration", "release", "" ]
While investigating the D language, I came across GDC, a D Compiler for GCC. I downloaded the version for MinGW from here: <http://sourceforge.net/projects/dgcc/files/> Documentation was almost nonexistent, but it did say that most of the command line switches were the same as for the GCC compiler. However, that doesn't help me much, since I don't usually build with GCC. GDC is described as a "GCC front end". That makes me think that at some point it has to generate intermediate C++ or C that the GCC compiler can actually swallow. I believe that this is how GCC compiles Objective-C programs. What I want to know is this: Is there a way to get GDC to emit the intermediate C/C++ code as files that I can then inspect and compile by hand with GCC/MinGW?
No. Front-ends to GCC generate a language-independent representation that is then compiled directly to assembly. This is the case for the C, C++, Obj-C, D, Fortran, Java, Ada, and other front-ends. There is no intermediate C or C++ representation, nor can one be generated.
Quick answer: no. From what I know about GCC, it uses [abstract syntax trees](http://en.wikipedia.org/wiki/Abstract_syntax_tree) for the language-independent code representation that gets passed from the front-end to the back-end. Theoretically it might be possible to "decompile" that AST to C/C++ code, but AFAIK the GCC suite does not implement this.
Make GDC front end emit intermediate C/C++ code?
[ "", "c++", "c", "gcc", "mingw", "d", "" ]