text
stringlengths
8
267k
meta
dict
Q: window.close() javascript method doesnt work in phonegap for iOS Im trying to close a popup window that has been opened using window.open() in my phonegap app being developed on iOS. But the window.close method doesnt work when Im trying to close the newly opened popup window. Although it works fine in normal web browsers, how can i make it work on the iphone simulator or atleast will it work on the final app deployed? tried alternate trick - window.open('','_parent');window.close(); too but to no use.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571347", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why In App Purchase goes to SKPaymentTransactionStateFailed? I have implimented In App Purchase in my application. when i try to buy a product it goes to SKPaymentTransactionStateFailed and gives the error message Can't connect to the iTunes Store when i press a button to buy product then this code is called MKStoreManager * manager = [MKStoreManager sharedManager]; [manager buyFeatureA]; the classes that i am using for purchase are given on these links MKStoreManager MKStoreObserver Please help me i am so much worried about this :( Thanx in advance A: Check carefully the product id that you are requesting to itunes Connect should be the same that is created in itunes for purchases. A: Guys in my case i didn't uploaded the application on App store. For In App Purchase we should upload our app on app store and when app is in "Waiting for review" state then reject your App Binary and then check In App Purchase in your App.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571349", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: php compare/match range of values I have an array to which I need to compare data from mysql. Usually I'm doing a straight comparison so I can do an if ($array[$i]===$mysql[$i]), but I do have one instance where I need to match it against a range of numbers (ex. 18-19, 20-24, etc). I looked into preg_match & preg_grep, but they don't seem to be what I want… I just need a true/false result from the comparison. The part of the array I'm trying to match against looks like this: "age"=>array( '18-19'=>array('total'=>0,'completed'=>0), '20-24'=>array('total'=>0,'completed'=>0), '25-29'=>array('total'=>0,'completed'=>0), '30-34'=>array('total'=>0,'completed'=>0), '35-39'=>array('total'=>0,'completed'=>0), '40-44'=>array('total'=>0,'completed'=>0), '45-49'=>array('total'=>0,'completed'=>0), '50-54'=>array('total'=>0,'completed'=>0), '55-59'=>array('total'=>0,'completed'=>0) ),"race"=>array( "White"=>array('total'=>0,'completed'=>0), "Black"=>array('total'=>0,'completed'=>0), "Hispanic"=>array('total'=>0,'completed'=>0), "Asian"=>array('total'=>0,'completed'=>0), "Pacific Islander"=>array('total'=>0,'completed'=>0), "Multiracial"=>array('total'=>0,'completed'=>0), "Other"=>array('total'=>0,'completed'=>0) ) Is there a clean way to do this? Thanks! A: list($min,$max) = explode('-', $array[$i]); if ($mysql[$i] >= $min && $mysql[$i] <= $max) ... A: PHP's range() function might be useful: foreach ($array['age'] as $ageRange => $something) { list($start, $limit) = explode('-', $ageRange); foreach (range($start, $limit) as $age) { // compare } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7571356", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: rand() function in c++ i am not quite sure how this function in c++ works: int rand_0toN1(int n) { return rand() % n; } Another tutorial on internet says to get a random number between a range you need to do something different however, with a being first number in range and n is number of terms in range: int number = a + rand( ) % n; I have read that it is supposed to return a random number between the value of 0 and n-1, but how does it do that? I understand that % means divide and give the remainder (so 5 % 2 would be 1) but how does that end up giving a number between 0 and n-1? Thanks for help in understanding this. I guess i don't understand what the rand() function returns. A: The modulo (remainder) of division by n > 0 is always in the range [0, n); that's a basic property of modular arithmetic. a + rand() % n does not return a number in the range [0, n) unless a=0; it returns an int in the range [a, n + a). Note that this trick does not in general return uniformly distributed integers. A: rand returns a pseudorandom value bewtween 0 and RAND_MAX, which is usually 32767. The modulo operator is useful for "wrapping around" values: 0 % 5 == 0 1 % 5 == 1 2 % 5 == 2 3 % 5 == 3 4 % 5 == 4 5 % 5 == 0 // oh dear! 6 % 1 == 1 // etc... As such, by combining that pseudorandom value with a modulo, you're getting a pseudorandom value that's guaranteed to be between 0 and n - 1 inclusive. A: According to your own example, you seems to understand how it works. rand() just returns an integer pseudorandom number between 0 and RAND_MAX, then you apply the modulo operator to that number. Since the modulo operator returns the remainder of division of one number by another, a number divided by N will always return a number lesser than N. A: The rand() function returns an integral value in the interval [0...RAND_MAX]. And the results of x % n will always be in the range [0...n) (provided x >= 0, at least); this is basic math. A: Please take a look here : http://www.cplusplus.com/reference/clibrary/cstdlib/srand/ Usually you "seed" it with the time function. And then use the modulus operator to specify a range. A: The c++ rand() function gives you a number from 0 to RAND_MAX (a constant defined in <cstdlib>), which is at least 32767. (from the c++ documentation) The modulus (%) operator gives the remainder after dividing. When you use it with rand() you are using it to set an upper limit (n) on what the random number can be. For example, lets say you wanted a number between 0 and 4. Calling rand() will give you an answer between 0 and 32767. rand() % 5, however, will force the remainder to be 0, 1, 2, 3, or 4 depending on the value rand() returned (if rand() returned 10, 10%5 = 0; if it returned 11, 11%5 = 0, etc.).
{ "language": "en", "url": "https://stackoverflow.com/questions/7571357", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Need a twin group by value I have a query something like this, SELECT SOME_ID, COUNT(ANOTHER_ID) AS WITHOUT_FILTER from SOME_TABLE GROUP BY SOME_ID this returns me +------------+------------------+ | SOME_ID | WITHOUT_FILTER | +------------+------------------+ | 1 | 40 | | 2 | 30 | +------------+------------------+ I have the same query with a condition which gives me filtered values. SELECT SOME_ID, COUNT(ANOTHER_ID) AS WITH_FILTER from SOME_TABLE WHERE SOME_COL > 10 GROUP BY SOME_ID which returns obviously lesser values in the grouped_by section +------------+----------------+ | SOME_ID | WITH_FILTER | +------------+----------------+ | 1 | 20 | | 2 | 15 | +------------+----------------+ Now, I need a query to give me both the count values ie with condition and without condition in one single query. The result should be like this +----------+----------------+---------------+ | SOME_ID | WITHOUT_FILTER | WITH_FILTER | +----------+----------------+---------------+ | 1 | 40 | 20 | | 2 | 30 | 15 | +------------+--------------+---------------+ Please help me. A: You can do this: SELECT SOME_ID, COUNT(ANOTHER_ID) AS WITHOUT_FILTER SUM(case when SOME_CONDITION then 1 else 0 end) AS WITH_FILTER from SOME_TABLE GROUP BY SOME_ID A: You can get a "COUNT, but only for the rows meeting a condition" effect by using IF() and SUM. SELECT SOME_ID, COUNT(ANOTHER_ID) AS WITHOUT_FILTER, SUM(IF(SOME_COL > 10, 1, 0)) AS WITH_FILTER FROM SOME_TABLE GROUP BY SOME_ID (Note: This solution, and all the others except Adrian's, has a subtle problem if ANOTHER_ID is ever NULL. If that's the case, then Adrian's is the only one that is truly correct). A: For learning purposes, here are my 2 cents. You can use COUNT on both fields: SELECT SOME_ID, COUNT(ANOTHER_ID) AS WITHOUT_FILTER COUNT(case when WHEN SOME_COL > 10 then ANOTHER_ID else NULL end) AS WITH_FILTER from SOME_TABLE GROUP BY SOME_ID The trick is that COUNT counts non-null values. This feature is ANSI SQL supported, BTW. A: try CASE and SUM combined: SELECT SOME_ID, COUNT(ANOTHER_ID) as WITHOUT_FILTER, SUM(CASE WHEN SOME_COL > 10 THEN 1 else 0 END) as WITH_FILTER from SOME_TABLE GROUP BY SOME_ID; A: SELECT T1.SOME_ID, COUNT(T1.ANOTHER_ID) AS WITH_FILTER, COUNT(T2.ANOTHER_ID) AS WITHOUT_FILTER FROM SOME_TABLE as T1, SOME_TABLE as T2 WHERE T1.SOME_ID=T2.SOME_ID AND T2.SOME_COL > 10 GROUP BY T1.SOME_ID, T2.SOME_ID Or you can do it with 2 views merging if your conditions become too touchy
{ "language": "en", "url": "https://stackoverflow.com/questions/7571358", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I insert a node before an other using dom4j? I have a org.dom4j.Document instance that is a DefaultDocument implementation to be specific. I would like to insert a new node just before an other one. I do not really understand the dom4j api, I am confused of the differences between Element and DOMElement and stuff. org.dom4j.dom.DOMElement.insertBefore is not working for me because the Node I have is not a DOMElement. DOMNodeHelper.insertBefore is nor good because I have org.dom4j.Node instances and not org.w3c.dom.Node instances. OMG. Could you give me a little code snippet that does this job for me? This is what I have now: // puts lr's to the very end in the xml, but I'd like to put them before 'e' for(Element lr : loopResult) { e.getParent().add(lr); } A: It's an "old" question, but the answer may still be relevant. One problem with the DOM4J API is that there are too many ways to do the same thing; too many convenience methods with the effect that you cannot see the forest for the trees. In your case, you should get a List of child elements and insert your element at the desired position: Something like this (untested): // get a list of e's sibling elements, including e List elements = e.getParent().elements(); // insert new element at e' position, i.e. before e elements.add(elements.indexOf(e), lr); Lists in DOM4J are live lists, i.e. a mutating list operation affects the document tree and vice versa As a side note, DOMElement and all the other classes in org.dom4j.dom is a DOM4J implementation that also supports the w3c DOM API. This is rarely needed (I would not have put it and a bunch of the other "esoteric" packges like bean, datatype, jaxb, swing etc, in the same distribution unit). Concentrate on the core org.dom4j, org.dom4j.tree, org.dom4j.io and org.dom4j.xpathpackages.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571369", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: jQuery disable scroll when mouse over an absolute div I'm trying to disable the window mouse scroll functionality when the mouse is hovering over the div - so that only div scrolling is enabled - and when mouse moves away from the div - scrolling to the window is applied again. The div is positioned absolutely. I've seen this post use jquery to disable mouse scroll wheel function when the mouse cursor is inside a div? but it doesn't seem to provide any answer - hence my question. I'm assuming it would be something like this (if only these methods existed): $('#container').hover(function() { $(window).scroll().disable(); $(this).scroll().enable(); }, function() { $(window).scroll().enable(); }); A: This has been a popular question so I am updating to give an overview of the answers provided here and which may be best for you. There are three unique solutions included. Two are from Amos and one is from myself. However, each operates differently. * *Amos - Set overflow:hidden on body. This is simple and works great. But the main window's scrollbars will flash in and out. *Amos - Use javascript to disable mouse wheel. This is great if you don't need mousewheel at all. *This answer - Use javascript to scroll only the element you are over. This is the best answer if your inner div needs to scroll, but you don't want any other divs to scroll. The example fiddle showcases this. http://jsfiddle.net/eXQf3/371/ The code works as follows: * *Catch scroll event on the current element *Cancel the scroll event *Manually scroll the current element only   $('#abs').bind('mousewheel DOMMouseScroll', function(e) { var scrollTo = null; if (e.type == 'mousewheel') { scrollTo = (e.originalEvent.wheelDelta * -1); } else if (e.type == 'DOMMouseScroll') { scrollTo = 40 * e.originalEvent.detail; } if (scrollTo) { e.preventDefault(); $(this).scrollTop(scrollTo + $(this).scrollTop()); } });​ Changelog: * *FF support *scrollTo null check to revert to default behavior in case something unforeseen happens *support for jQuery 1.7. A: You cannot disable window scroll, there is a simple workaround though: //set the overflow to hidden to make scrollbars disappear $('#container').hover(function() { $("body").css("overflow","hidden"); }, function() { $("body").css("overflow","auto"); }); See demo: http://jsfiddle.net/9Htjw/ UPDATE You can disable the mouse wheel though. $('#container').hover(function() { $(document).bind('mousewheel DOMMouseScroll',function(){ stopWheel(); }); }, function() { $(document).unbind('mousewheel DOMMouseScroll'); }); function stopWheel(e){ if(!e){ /* IE7, IE8, Chrome, Safari */ e = window.event; } if(e.preventDefault) { /* Chrome, Safari, Firefox */ e.preventDefault(); } e.returnValue = false; /* IE7, IE8 */ } Source: http://solidlystated.com/scripting/javascript-disable-mouse-wheel/ Demo: http://jsfiddle.net/9Htjw/4/ A: mrtsherman: if you bind the event like this, amosrivera's code works also for firefox: var elem = document.getElementById ("container"); if (elem.addEventListener) { elem.addEventListener ("mousewheel", stopWheel, false); elem.addEventListener ("DOMMouseScroll", stopWheel, false); } else { if (elem.attachEvent) { elem.attachEvent ("onmousewheel", stopWheel); } } A: I used nicescroll on my page no method worked. I realized the nicescroller is calling the scroll event and had to temporarily disable nicescroll when hovering the element. Solution: Temporarily disable nicescroll when hovering an element $('body').on('mouseover', '#element', function() { $('body, html').css('overflow', 'auto').getNiceScroll().remove(); }).on('mouseout', '#element', function() { $('body, html').css('overflow', 'hidden').niceScroll(); }); A: What I'm trying to do here with my code is: * *Check if div is hovered over or moused over *Get the scroll direction *Compare the ScrollTop with the Height of the container and prevent further scroll when max or min is reached(until moused is out). var hovered_over = false; var hovered_control; function onCrtlMouseEnter(crtl) { //Had same thing used for mutliple controls hovered_over = true; //could be replaced with $(control).onmouseenter(); etc hovered_control = crtl; //you name it } function onCrtlMouseLeave(crtl) { hovered_over = false; hovered_control = null; } $(document).on("mousewheel",function(e) { if (hovered_over == true) { var control = $(hovered_control); //get control var direction = e.originalEvent.wheelDeltaY; //get direction of scroll if (direction < 0) { if ((control.scrollHeight - control.clientHeight) == control.scrollTop) { return false; //reached max downwards scroll... prevent; } } else if (direction > 0) { if (control.scrollTop == 0) { return false; //reached max upwards scroll... prevent; } } } }); http://jsfiddle.net/Miotonir/4uw0vra5/1/ Probably not the cleanest code and it can be improved upon easily, but this works for me. (control.scrollHeight - control.clientHeight) this part is kindoff questionable for me , but you should get the idea how to approach the problem anyways. A: @mrtsherman's Answer almost worked for me, but there was a breaking change with passive scrolling in Chrome. preventScrollingEl = document.getElementById("WHATEVER"); preventScrollingEl.addEventListener('mousewheel', preventScrolling, {passive: false}); preventScrollingEl.addEventListener('DOMMouseScroll', preventScrolling, {passive: false}); function preventScrolling(event) { var scrollTo = null; if (event.type == 'mousewheel') { scrollTo = (event.wheelDelta * -1); } else if (event.type == 'DOMMouseScroll') { scrollTo = 40 * event.detail; } if (scrollTo) { event.preventDefault(); $(this).scrollTop(scrollTo + $(this).scrollTop()); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7571370", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "55" }
Q: Spring AOP Configuration (XML) I am experimenting with Spring AOP for the first time and get stuck in the XML configuration. I'm trying to get a mock version of AOP-based "logging" up and running, using a MethodInterceptor to wrap specific method calls and do some simple System.out.println statements before and after those method invocations. Simple stuff, right? So my project has many classes, two of them are Fizz and Buzz. Fizz has a method named foo() and Buzz has a method named wapap(). Every time these methods are invoked at runtime, I want my LoggingInterceptor to execute its invoke() method around them: public class LoggingInterceptor implements MethodInterceptor { public Object invoke(MethodInvocation methodInvocation) { try { System.out.println("About to call a special method."); Object result = methodInvocation.proceed(); return result; } finally { System.out.println("Finished executing the special method."); } } } So I understand the concepts of advice (my interceptor impl), pointcuts (the methods that will have advice executed around them), and pointcut advisors (bindings between advice and pointcuts). I'm just struggling tying it altogether in a simple XML config. Here's what I have so far, but I know it's missing pointcut and pointcut advisor definitions, and possibly more. <beans default-autowire="no" > <bean name="loggingInterceptor" class="org.me.myproject.aop.LoggingInterceptor"/> </beans> What am I missing here to make this specific to Fizz::foo() and Buzz::wapap() calls? Any nudges in the right direction are enormously appreciated! A: Add this: <aop:config> <aop:advisor advice-ref="loggingInterceptor" pointcut="execution(public * Fizz.foo(..))"/> <aop:advisor advice-ref="loggingInterceptor" pointcut="execution(public * Buzz.wapap(..))"/> </aop:config> You also need to add AOP namespace declaration in version appropriate to your framework: <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd "> Also consider using @AspectJ aspects and see this question: Spring: Standard Logging aspect (interceptor). A: If you are using Spring 2.5+ you can use annotation to and create your advice and Pointcuts. Create class with @Aspect annotation. Create @PointCut for specific class and specific method and then create @Around advice. You can read short tutorial how to do it here: http://veerasundar.com/blog/2010/01/spring-aop-example-profiling-method-execution-time-tutorial/ It' very easy to implement.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571371", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do massively scalable sites like Facebook and Google implement sessions? Does anyone have any insight into their system architecture? Do they use Memcache? Surely every time I click on Facebook my HTTP requests aren't being channeled to the same server where my session is in memory? A: A basic solution would be to store the session identifier & associated state in a database (or equivalent). This allows any application node in a cluster to access the session. In practice, such a solution is slow and read-through caching (e.g. with Memcache), session replication, etc. are used to improve performance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571376", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Create a collection in XAML and bind individual collection items I've created a custom control which, when bound to a custom collection of objects, displays the content of those objects. Usually, I can use this control by simply going: <local:CustomCollectionDisplayer DataContext="{Binding Source={x:Static Application.Current}, Path=SomeObject.InstanceOfCustomeCollectionOfCustomItems}" /> My problem now comes where I want to recycle this control to show only a single object. In the xaml, I want to make a custom collection where the only item in the collection is bound to that single object. The code looks like this: <local:CustomCollectionDisplayer> <local:CustomCollectionDisplayer.DataContext> <local:CustomCollection> <local:CustomItem Reference="{Binding Source={x:Static Application.Current}, Path=SomeObject.InstanceOfCustomItem}"/>--> </local:CustomCollection> </local:CustomCollectionDisplayer.DataContext> </local:CustomCollectionDisplayer> Obviously, there's no 'Reference' property which I can use to make the CustomItem in the collection point to the instance of CustomItem in 'SomeClass'. How can I achieve this without creating a dummy CustomCollection containing this CustomItem in my object viewmodel? A: There already is a x:Reference markup extension, but it is very limited as it only gets objects by name. You could write your own markup-extension which can get properties. e.g. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Markup; using System.ComponentModel; namespace Test.MarkupExtensions { [ContentProperty("Object")] public class GetExtension : MarkupExtension { public object Object { get; set; } public string PropertyName { get; set; } public GetExtension() { } public GetExtension(string propertyName) : this() { if (propertyName == null) throw new ArgumentNullException("propertyName"); PropertyName = propertyName; } public override object ProvideValue(IServiceProvider serviceProvider) { if (PropertyName == null) throw new InvalidOperationException("PropertyName cannot be null"); if (Object == null) { var target = (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget)); Object = target.TargetObject; } var prop = Object.GetType().GetProperty(PropertyName); if (prop == null) throw new Exception(String.Format("Property '{0}' not found on object of type {1}.", PropertyName, Object.GetType())); return prop.GetValue(Object, null); } } } Which could be used like this: <local:CustomCollectionDisplayer> <local:CustomCollectionDisplayer.DataContext> <local:CustomCollection> <me:Get PropertyName="InstanceOfCustomItem"> <me:Get PropertyName="SomeObject" Object="{x:Static Application.Current}"/> </me:Get> </local:CustomCollection> </local:CustomCollectionDisplayer.DataContext> </local:CustomCollectionDisplayer> You could also resolve a whole PropertyPath at once in the extension if you prefer that, this is just a sketchy example. Another option is to bind the DataContext directly to the object and wrap it in the collection using a Converter.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571377", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do you develop for cross browser compatibility? How do you develop for cross browser compatibility? How do you develop and ensure that end products are capable of running on most browsers? JavaScript and DOM: JQuery EXT JS CSS: CSS Mastery (Book resource) What other techniques do you employ? A: There are a wide range of books that cover certain areas of the subject. You also need to be aware of CSS bugs exhibited by certaIn browseErs. You may wish to read something like CSS Mastery, for example. You can use something like http://browsershots.org to test your design in a wide range of browsers before launching. A: Google these phrases/trends: * *graceful degradation *progressive enhancement *responsive design *design for mobile first *ARIA standards For the most part, it's not too hard: hire good designers (visual, UX, dev) that understand the medium. Code to standards and best practices. Ignore IE if you are allowed to. ;)
{ "language": "en", "url": "https://stackoverflow.com/questions/7571380", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Building with Build.exe and dirs/sources and Visual Studio 2010/11 * *Is there any way to tell Visual Studio 2010 (or Visual Studio 11 Developer Preview) to use a sources file? *Is there any tools for converting from nmake/dirs/sources to MSBuild? I really want to use the Visual Studio 11 Developer Preview Code Analysis tools on a very old C++ solution, which currently doesn't even come close to being able to compile in Visual Studio. Here's an example of one of the many sources files: !INCLUDE $(INETROOT)\build\paths.all !INCLUDE $(INETROOT)\build\sources.all TARGETNAME=CSDWCtlg TARGETTYPE=DYNLINK DLLENTRY=DllMainCRTStartupCustom DLLDEF= USE_NATIVE_EH=1 NO_NTDLL=1 NTTARGETFILE0=$(EXPORTED_FILES) INCLUDES= \ $(INCLUDES); \ $(SDK_INC_PATH); \ $(ATL_INC_PATH); \ $(CSSTORAGE)\inc; \ $(CSSTORAGE)\util\inc; \ $(CSSTORAGE)\dbg; \ $(CSSTORAGE)\msg; \ $(CSSTORAGE)\intf\idl; \ $(CSSTORAGE)\ctlg; \ $(CSSTORAGE)\provider; \ $(CSSTORAGE)\dsproviders\inc\; \ $(CSCOMMON)\rockall4\Build\Rockall\Include; \ $(CSCOMMON)\rockall4\Code\Rockall\Interface; \ $(CSCOMMON)\kbase; \ $(CSCOMMON)\inc; \ # goes to both RC compiler and C compiler # RUN_WPP=$(SOURCES) -func:{LEVEL=Error}ErrorTrace(ERR,MSG,...) -func:{LEVEL=Debug}DebugTrace(DBG,MSG,...) C_DEFINES=$(C_DEFINES) /D_UNICODE /DUNICODE /DPROJ_METABASE /DCSTRACE_CSDWCTLG /D_CTLG_DIAGNOSTIC#1 USER_C_FLAGS=$(USER_C_FLAGS) -D_CTLG_DIAGNOSTIC=1 -GR -D_WIN32_WINNT=0x0500 -DOLEDBVER=0x0250 # check for 64-bit compatiblitly !if "$(PROCESSOR_ARCHITECTURE)"=="x86" USER_C_FLAGS = $(USER_C_FLAGS) /Wp64 !endif # The line below includes the common build flags. # It modifies the USER_C_FLAGS variable by appending the 'project' level flags. # Be sure to use the syntax USER_C_FLAGS=$(USER_C_FLAGS) 'flags' if you use USER_C_FLAGS after this include. !INCLUDE $(CSSTORAGE)\inc\userFlags$(DCRT).inc USE_MSVCRT=1 PRECOMPILED_CXX=1 PRECOMPILED_INCLUDE=pch.hpp PRECOMPILED_PCH=pch_hpp.pch PRECOMPILED_OBJ=pch_hpp.obj SOURCES=\ csdwctlg.rc \ pch.cpp \ dll.cpp \ crow.cpp \ ctlgdump.cpp \ ctlghandler.cpp \ ctlgobj.cpp \ ctlgobjaccess.cpp \ ctlgobjclsdef.cpp \ ctlgobjdefs.cpp \ ctlgobjget.cpp \ ctlgobjkeydef.cpp \ ctlgobjmemdef.cpp \ ctlgobjrel.cpp \ ctlgobjrow.cpp \ ctlgobjset.cpp \ ctlgobjtbl.cpp \ ctlgobjtbls.cpp \ ctlgobjtypedef.cpp \ ctlgobjview.cpp \ ctlgpersist.cpp \ ctlgresolve.cpp \ ctlgresolve2.cpp \ ctlgpartresolve.cpp \ ctlgaggrresolve.cpp \ ctlgfilterresolve.cpp \ ctlgvalidate.cpp \ expschema.cpp \ mbcatalog.cpp \ mbictlgchg.cpp \ schemamgr.cpp \ sqlpathtrans.cpp \ TARGETLIBS= \ $(DEFAULTLIBS) \ $(SDK_LIB_PATH)\ole32.lib \ $(SDK_LIB_PATH)\oleaut32.lib \ $(SDK_LIB_PATH)\uuid.lib \ $(SDK_LIB_PATH)\urlmon.lib \ $(TARGETPATH)\*\CSDWIntf.lib \ $(TARGETPATH)\*\CSDWUtil.lib \ $(SDK_LIB_PATH)\msi.lib \ $(TARGETPATH)\*\csrockall.lib \ $(TARGETPATH)\*\CSDWSrvrDLL.lib \ $(SDK_LIB_PATH)\Kernel32.lib \ $(SDK_LIB_PATH)\user32.lib \ $(SDK_LIB_PATH)\Advapi32.lib \ $(CRT_LIB_PATH)\oldnames.lib \ $(SDK_LIB_PATH)\atls$(DCRT).lib \ # For Binplacing MISCFILES= \ .\SCHEMA\* \ Any advice? UPDATE: I've found nmake2msbuild.exe which is part of the WDK. It is intended for driver development and converts dirs and sources to MSBuild projects. I am not sure if it's going to work for what I have to do (not drivers), but I'm going to give it a try. A: I've found nmake2msbuild.exe which is part of the WDK. It is intended for driver development and converts dirs and sources to MSBuild projects. Some manual tweaking of the sources files was required to get the tool to complete conversion. It doesn't do everything, but helps get things on track.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571383", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Regexp match any character except a particular string I am using the regexp, /(\<\s*?string(-array)?\s*?.*?\s*?\>\s*?)(.*)(\s*?\<\/string(-array)?\>)/ ... to match all content between or tags of the form: <string-array name="saveArray"> <item>Téléphone</item> <item>Carte mémoires</item> </string-array> Problem is, I'm only able to match the contents of 'string' tags or arrays containing one item. When I replace the dot from the captured group in the middle with [^s], I get the content I want, but this solution would fail to match any content containing 's'. I tried a negative look-behind for 'str' immediately preceding the content ('item-matching') group, and it is giving me the same results. Any help would be great! A: You need to use SimpleXML to parse XML. The XML may change or not match your regex in edge cases - so it's best to just use an XML parser. <?php $xml '<string-array name="saveArray">' . '<item>Téléphone</item>' . '<item>Carte mémoires</item>' . '</string-array>'; $items = new SimpleXMLElement($xml); A: As others have said do not use regex to parse xml/html. In any case this should work : if ($subject =~ m!<(string-array)[^>]*>(.*?)</\1>!si) { print $2, "\n"; } A: You really should not parse xml using regexps. That said, I think the thing that's messing you up might be that "." (in many regexp engines, with default flags) matches any character except a newline.. So your .* will not match more than one line. Try replacing ".*" with "[\w\W]*", or adding a regexp flag that says that "." should match all characters.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Zend clear Request Parameters I just wanted to ask why the following inside a Zend_Controller_Action action method: $request = $this->getRequest(); $params = $request->getParams(); var_dump($params); foreach ($params as $key => &$value) { $value = null; } var_dump($params); $request->setParams($params); var_dump($request->getParams()); produces this: array 'controller' => string 'bug' (length=3) 'action' => string 'edit' (length=4) 'id' => string '210' (length=3) 'module' => string 'default' (length=7) 'author' => string 'test2' (length=5) array 'controller' => null 'action' => null 'id' => null 'module' => null 'author' => null array 'author' => string 'test2' (length=5) Shouldn't the 'author' variable be cleared too? Thanks in advance! A: The getParams method is shown below. What happens is you're clearing the built in params (controller, action etc...) but the method always returns GET and POST variables. /** * Retrieve an array of parameters * * Retrieves a merged array of parameters, with precedence of userland * params (see {@link setParam()}), $_GET, $_POST (i.e., values in the * userland params will take precedence over all others). * * @return array */ public function getParams() { $return = $this->_params; $paramSources = $this->getParamSources(); if (in_array('_GET', $paramSources) && isset($_GET) && is_array($_GET) ) { $return += $_GET; } if (in_array('_POST', $paramSources) && isset($_POST) && is_array($_POST) ) { $return += $_POST; } return $return; } A: To clear params you can simply call: $request->clearParams();
{ "language": "en", "url": "https://stackoverflow.com/questions/7571391", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Change img src in ASP.NET with Ajax I have a .aspx page with an <img> tag which has an src subject to change depending on some controls values on the page. Pratically I change src with a runtime built-in querystring that cause src change and and wait for server response (server is returning a byte[] of the image). My issue is that my <img> flicker (it becomes white) while is waiting for server's response. How can I update it once the server has done? Can JavaScript and JQuery accomplish this? Thanks in advance! A: You can preload the image and set it when it's preloaded like this: $('<img>').attr('src', 'path/to/image/you/want/to/preload.png') .bind('load', function() { $('#image-to-replace').attr('src', $(this).attr('src')); }); With jQuery, this creates an <img>, sets its src attribute and attaches an event handler to the image's load event so that when the image is done loading, you can set the image's src to whatever #image-to-replace you have in your markup.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571392", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: RubyGems Dependency Error My ruby version is => ruby 1.9.2p290 (2011-07-09 revision 32553) [i686-linux] and I'm using Ubuntu 10.10. I installed every stuff following this blogpost. It was working fine on bash but when I installed zsh shell and oh-my-zsh then it started raising following dependency error: /home/manish/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/dependency.rb:247:in `to_specs': Could not find rails (>= 0) amongst [minitest-1.6.0, rake-0.8.7, rdoc-2.5.8] (Gem::LoadError) from /home/manish/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/dependency.rb:256:in `to_spec' from /home/manish/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems.rb:1210:in `gem' from /home/manish/.rvm/gems/ruby-1.9.2-p290/bin/rails:18:in `<main>' Please tell me if there is any way to fix this. P.S. => I have installed bundler gem. I also tried to uninstall rvm and reinstall but didn't worked. A: Oh crap this sucks. I already had rvm script [[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" in my ~/.zshrc but it use to say following error in my zsh shell every time: cd:cd:10: string not in pwd: .. then i rewrote the same script again following the previous one i.e. running same script twice in ~/.zshrc, it WORKED. I still could not figure it out why it raises string not in pwd.... error on first script and runs the second one. But yay! feels good to finally use zsh on my Ubuntu also :) A: From looking at your rvm info it seems that this isn't quite right: homes: gem: "not set" ruby: "not set" I would have another crack at reinstalling rvm, it shouldn't be that difficult. If you're having problems then you can ask on the channel #rvm on the freenode IRC network. Other things to try would be rvm reload followed by rvm 1.9.2.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571394", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Installing windows service fails: service already exists I'm trying to reinstall a service I've written using C#. The first time this worked. I used installutil to handle the install and the service showed up in the list of services and I could start it. Then I made some updates to the code and uninstalled the service. After figuring out I had to close the services window, the service seemed to have disappeared (i.e. successfully uninstalled). However, upon trying to install the service again I got the message saying: System.ComponentModel.Win32Exception: The specified service already exists This seemed strange as I couldn't see it in the services window. I finally thought I found the problem after deleting a registry key regarding my service, but unfortunately this didn't solve anything. Also, uninstalling again doesn't do much to solve the problem as this results in the contradictory message: System.ComponentModel.Win32Exception: The specified service does not exist as an installed service What should I believe? Does or doesn't the service exists? I feel like a physicist trying to figure out whether the cat is dead or alive. I hope someone here knows something to help solve this problem. A: A related SO-answer finally pointed me in the right direction (why I didn't find that in Google or SO's own search I don't know). Anyway, apparently the Designer.cs generated by Visual Studio also creates a process- and service-installer. Which of course install services with the same name as my manually created installers. Removing my own installers solved the problem. A: Actual issue is that you have added the object of serviceProcessInstaller & serviceInstaller multiple times in your code .. It should only be added once.. Open the designer.cs file of projectinstaller you will see it is already added there... A: I was also getting the same error, so to resolve, what I did was: * *Open the ProjectInstaller.cs from solution Explorer *Go into view designer mode by right clicking, if code view is there You will see a new installer apart from defaults 2, i.e. serviceprocessInstaller1 and ServiceInstaller1. Just remove that installer which was automatically generated. Now build and install, it will work. A: Check the Service Name Property in Service Installer. A: I have tried all solution mentioned above. But my service was installed with some different name in registry. So just try to delete that registry. Open below link in registry Hkey_Local_Macine>System>CurrentControlSet>Service> But I didnt find my service under this path. So I tried to find it out in registry. Just press ctrl + F and give the name of your service. or some guess name. You will get the exact location. Just delete it. It will work. A: Need to remove "Me.Installers.AddRange(New System.Configuration.Install.Installer() {Me.ServiceInstaller1, Me.ServiceProcessInstaller1})" line if same line is there already in designer, then it will get installed. ServiceProcessInstaller1 is name in my project.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571396", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: ie 7 and below issue, absolute positioning for some reason in ie 7 and lower there is a huge gap in the content. I think it has to do with some jQuery I have running. the menu seems to push the content down even though its absolute position and it shouldn't be in the flow? http://www.tigerstudiodesign.com/company-overview/ ie 7 and below: http://localhostr.com/files/yshCtut/Screen+shot+2011-09-27+at+11.08.20+AM.jpg what it should look like: http://localhostr.com/files/Gq1DiuR/Screen+shot+2011-09-27+at+11.08.40+AM.jpg A: try this #header {position: relative;} #content {position: absolute; left: 0; top: 135px; height: 40px; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7571397", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I reset the values in javascript without using .animate, related with jquery I'm changing this div's (#logo)attributes like this $('#logo').stop().animate({ left: 150, height: 78, marginTop: 45 } After 2 seconds after animation is finished, I make it disappear with .hide('slow'), now while it is hidden I wan't to change it's attributes the same left, height and marginTop to old default ones without animation, because when I do through animate it appears. I mean becomes display:block. I want to make this hidden and then fideIn. A: You can use .css in a callback which runs once the animation is complete: $('#logo').stop().animate({ left: 150, height: 78, marginTop: 45 }, function() { $(this).css({ left: 150, //Change these to whatever they were before the call to animate height: 78, marginTop: 45 }).fadeIn(); }); A: Just use the jQuery css function to set the properties back to their original values. $('#logo').stop().animate({ left: 150, height: 78, marginTop: 45 }).hide('slow', function() { $(this).css({ left: 0, height: 50, marginTop: 10 }).fadeIn(); }); JSFiddle Example
{ "language": "en", "url": "https://stackoverflow.com/questions/7571401", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: handle OnCompleted with cold observables in Rx, the following code does not seem to call my OnCompleted action? No "Sequence Completed" static void Main(string[] args) { var list = new List<int> { 1, 2, 3 }; var obs = list.ToObservable(); IDisposable subscription = obs.SubscribeOn(Scheduler.NewThread).Subscribe(p => { Console.WriteLine(p.ToString()); Thread.Sleep(200); }, p => Console.WriteLine("Sequence completed")); Console.ReadLine(); subscription.Dispose(); } Am i doing something silly, as there is no "Sequence Completed" printed after 3 in the Console window? Console Output 1 2 3 _ So, the prime focus of my question is how to run some code after this type of sequence has been iterated? * *E.g. how to execute Console.WriteLine("Sequence completed")) after all elements in the original list have been observed? *Please note that the .ToObservable originated from an IEnumerable (a List<> in this case) *And the subscription is run on a NewThread A: The problem is that the 2nd parameter to .Subscribe is the error callback. Your "sequence completed" string would be printed only if there was an error observing the elements. Here's the corrected code: var list = new List<int> { 1, 2, 3 }; var obs = list.ToObservable(); var subscription = obs.SubscribeOn(Scheduler.NewThread).Subscribe(p => { Console.WriteLine(p.ToString()); Thread.Sleep(200); }, error => Console.WriteLine("Error!"), () => Console.WriteLine("sequence completed")); Console.ReadLine(); subscription.Dispose();
{ "language": "en", "url": "https://stackoverflow.com/questions/7571406", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Need ideas on how to protect .exe file from direct download on other sites We have our application stored on our server, it is an .exe file. The download page is only accessible from our site - using cookie authentication in PHP. I know there are better methods but there is a long story behind this...so I'm moving on. The issue is that the actual url of the .exe has been leaked and is appearing on other websites. What is the best method to protect a link to a file, not the page itself. That is where I'm having issues. I can make it difficult to get to the download page (with the link) but don't know where to begin to make sure the link is only accessible from our site... Is .htaccess (preventing hotlinking) the best way to go? A: Yes, .htaccess is probably best. Find any online post about protecting images from hotlinking, the first in my google search looks like a nice and easy auto-generator you can use. Just change the image extensions to exe, or keep them if you want them protected too.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571407", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Evaluation of as.integer(max(factorize(15))) This appears quite bizarre to me and I would like an explanation. I library(gmp) factorize(15) # => "3" "5" max(factorize(15)) # => "5" as.integer("5") # => 5 as.integer(max(factorize(15))) # => 1 0 0 0 1 0 0 0 1 0 0 0 5 0 0 0 I can do what I want with: max(as.numeric(factorize(15))) # => [1]5 But it shook me that I couldn't rely on nesting functions inside of functions in a supposedly scheme-like language. Am I missing anything? A: Well, the answer is in the representation of factorize(15): > dput(factorize(15)) structure(c(02, 00, 00, 00, 01, 00, 00, 00, 01, 00, 00, 00, 03, 00, 00, 00, 01, 00, 00, 00, 01, 00, 00, 00, 05, 00, 00, 00), class = "bigz") and > dput(max(factorize(15))) structure(c(01, 00, 00, 00, 01, 00, 00, 00, 01, 00, 00, 00, 05, 00, 00, 00), class = "bigz") ...max and as.numeric (actually, as.double) have methods for the bigz class, but apparently as.integer does not: > methods(max) [1] max.bigq max.bigz > methods(as.numeric) no methods were found > methods(as.double) [1] as.double.bigq as.double.bigz as.double.difftime as.double.POSIXlt > methods(as.integer) no methods were found ...so as.integer treats the bigz objects as a simple vector of values. A: The result of factorize in package gmp is a object of class bigz: > factorize(15) [1] "3" "5" > str(factorize(15)) Class 'bigz' raw [1:28] 02 00 00 00 ... From the help for ?biginteger it seems the following coercion functions are defined for objects of class bigz: * *as.character *as.double Notice there is no as.integer in the list. So, to convert your result to numeric, you must use as.double: > as.double(max(factorize(15))) [1] 5 A: I agree that it seems odd that the 'bigz' class does not have an as.integer method. However, it may be that the whole point of the gmp package is to keep its values "out of the hands" of the less capable regular R representation structures. The authors did not choose (yet) to offer an integer coercion function but you could always suggest to them that they should. As @Andrie demonstrated, such a function can be defined to intercept what would otherwise would be a .Primitive call, which is what you now get with as.integer(). require(gmp) methods(as)
{ "language": "en", "url": "https://stackoverflow.com/questions/7571409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Does Entity Framework store it's DbContext along with cached query plans? In my web application, we are using a per request DbContext. We create the DbContext in Application_BeginRequest(), store it in HttpContext.Items, and then call Dispose on it in Application_EndRequest(). We make the current context available through a wrapper class DatabaseContext.Current property. Sporadically, when executing a query against this database context, we get the following exception: "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection". I've searched our code for any possibility that we are calling Dispose on the context elsewhere....we aren't. A query that commonly fails is this one: var user = (from u in DatabaseContext.Current.Users where u.UserName == username select u).FirstOrDefault(); return user != null; All I can think of is that deep in the bowels of the EF it is keeping a reference to the DbContext in a cached query plan and then attempting to reuse that context when the query is executed. I've looked at it through reflector and it does seem that some of the internals keep a reference to the ObjectContext. Is there a way to disable linq query caching? Anyone have any clues? The other possibility is that a query from a previous call on the Context is leaving the Context in bad state. However, there are no indications of failures that would indicate this. This is Entity Framework 4.1 using Sql CE (for now, we are soon migrating to a production SQL Server Instance). A: Neither of your scenarios should happened. There is no caching you mentioned. There are some possibilities you should check instead: * *You are using context after EndRequest or outside of current HttpRequest scope *You are storing entity retrieved from context somewhere in cache or session and using it in other request processing - this can be an issue because entity can keep reference to disposed context and use it for some operations. There is no automatic LINQ query caching - it is feature planned for upcoming EF release but that feature caches DbCommand instances independent on the context. A: You get this exception "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection" - because there is a failed transaction, after that trying to access a data query. Put a try catch and observe the exception. precisely, there is an exception, which is not handled properly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571412", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I use git rebase to transform my working tree exactly the way I want to? * 080dc7a (HEAD, origin/master, origin/HEAD, master) * bfeee2f |\ | * 16e94ff (origin/McLongNumber, McLongNumber) | * f50319b | |\ These are the last 4 commits of my working tree. I would like to rebase so that my working tree looks like the following example by squashing the last commit to the merge, preserving the rest of the tree exactly the way it is: * bfeee2f (HEAD, origin/master, origin/HEAD, master) |\ | * 16e94ff (origin/McLongNumber, McLongNumber) | * f50319b | |\ I already tried using --onto -p and -i without any success. Even by using the -p option when I managed to successfully squash the last commit, the tree line that showed the merge of McLongNumber to the master branch was lost from the log. So I guess someone who is more familiar with the rebase command can help me out on this. A: You can do it like this: # make 'master' point to it's parent commit, # but don't modify the index or working directory git reset --soft HEAD^ # rewrite the commit using the stuff in the index git commit --amend # publish the modified commit (see WARNING below) git push -f Note that the SHA1 will change; it will no longer be bfeee2f. WARNING It's almost always a VERY BAD idea to rewrite history that has already been published to a shared repository. Most shared repositories are configured to reject history modifications, even if the -f option to git push is used. Thus, you might not be able to do what you want anyway. The only times it is acceptable to rewrite published history are: * *You are the only person using the upstream repository and you know how to recover from a history rewrite in your other clones. *The other users of the shared repository know how to recover from rewritten history AND you've warned them that you've rewritten the history AND you've taken care to make sure important changes won't be discarded when you force push. Even so, rewriting history is highly disruptive to others; it's a great way to seriously annoy your co-workers/collaborators/contributors.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571418", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CSS responsive horizontal centering I was trying to horizontally center an image (logo) for every screen size doing something like this #container {position:relative width:100%; height:100%;} #logo {position:absolute; top:0; left:50% width:500px; height:100px;} and it's not working. Do I maybe have to use a width for container in pixels? A: #logo {margin-right:auto; margin-left:auto; width:500px; height:100px;} A: #logo { height:100px; margin:0 auto; width:500px; } This is the standard way of centering an image by telling it to automatically determine the space on both the left and right of a fixed size container. And an example. A: I guess it depends on how you define "responsive", but if you mean responsive in the sense that content resizes to accomodate the width of the viewport, then all of the other answers don't meet this criteria since they rely on fixed pixel widths. For example, what happens if the view port is less than 500px? A similar concept will work with percent widths, and actually be responsive, in that the thing you're centering will be flexible too: #container { width:100%; height:100%; position:fixed; left:0; right:0; z-index:100;} #logo { position:fixed; width:80%; z-index:101; left:50%; margin: 10% auto auto -40%;} If you don't want the "logo" element to get to big (on huge screens), you can add max-width:600px; to limit it, but you'd need to add some media-queries to keep it properly centered on large screens.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571419", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to ignore some folders in HG? Starting here, I'm wrestling with this right now. I've got two folders: Source and SQL. Source has multiple project folders. The project folders in Source and SQL have bin folders. I want to ignore all files in bin folders under Source, but not under SQL. I thought one of these might do the trick: glob:Source\*\bin\ glob:Source\*\bin glob:Source\*\bin\* glob:Source\*\bin* glob:Source*\bin\ glob:Source\*bin\ But no dice on all of the above. It seems I'll have to enter a line for each folder under Source where I expect to have a bin folder (and then update my .hgignore file whenever I add a new project). glob:Source\Project1\bin\ glob:Source\Project2\bin\ #etc If this is not the case, any advice would be appreciated. A: Have you tried a regexp: syntax: regex ^Source/.*/bin Also, do remember that anything you've already added isn't affected by ignore rules, so you need the files to be untracked to test this stuff. Lastly, consider making each project a separate repo -- that's the standard advice in DVCS land be it Mercurial or git. In svn multiple projects in the same repo isn't such a bad idea because you can have different parts of the working directory updated to different revisions, but with a DVCS all files are updated/checkedout to the same revision, which makes putting multiple Projects in the same repo a hassle in general and a really bad idea in some circumstances. A: Looking at my .hgignore file, my slashes seem to to be the other way around (a forwrad slash instead of a backslash). i.e: glob:*/bin/* Try that maybe?
{ "language": "en", "url": "https://stackoverflow.com/questions/7571421", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How can I change an encryption key and still be able to decrypt old data? I would need to create a symmetric key in C# and use it to encrypt a string, which I would eventually store in a database. I would use the AES mechanism in .Net to achieve this. I would use the same key to decrypt the encrypted data. Now my requirement is that if I have a mechanism to change the key. How can I ensure that I can use the newly created key to be used to decrypt the strings encrypted with the old or expired key? A: Everything in the database must be decrypted then re-encrypted with the new key every time the key changes. EDIT-- Per your comment, what Key_Source and Identity_Value is doing is creating a key that never changes then encrypting that key and changing that outer layer on regular intervals. I would not recommend implementing this yourself, as it is very hard to secure that master key correctly, and just use the key system built in to MS SQL if that is the database you are using.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571426", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there any add-ons in spring roo that can be used for Spring social? Is there any add-ons in spring roo that can be used for Spring social? Any help would be appreciated. A: As for now, there doesn't seem to be any. Please see the following discussion on the SpringSource forums. http://forum.springsource.org/showthread.php?111418-Add-on-for-spring-social-in-spring-roo
{ "language": "en", "url": "https://stackoverflow.com/questions/7571427", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: maven super pom's profile properties inheritance at child poms at my project there is 2 profiles and each profile has one property. But I could not use master's properties at child's resources. Here is described clearly but it seems that there is only one pom file and the sample shown at there is not an multi-module maven project. All I want to do is use this properties at spring level like changing the location of properties file. <profile> <id>p1</id> <properties> <properties.location>file:/apps-core1.properties</properties.location> </properties> </profile> <profile> <profile> <id>p2</id> <properties> <properties.location>file:/apps-core2.properties</properties.location> </properties> </profile> <profile> and I want to use "properties.location" at every pom file I had, either main-resources or test-resources. here is the spring usage <context:property-placeholder location="\${properties.location}" /> A: i got it working with a multi-module project with: * *parent pom with <modules /> config and your profiles *module pom with following config <build> <resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> <includes> <include>**/*.xml</include> </includes> </resource> </resources> </build> see maven resources and filtering
{ "language": "en", "url": "https://stackoverflow.com/questions/7571428", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: In Reporting services, how do I add an image from a string or cell in the table? What I'm trying to do is this: I have a string with the full path to the image. I tried to add an external image to my report and set the image source to my string. but every time I load the report, it doesn't load the image. How do I do this, or is there a better way of doing this? Thank you A: For an External image, the image source needs to be a URL for the image. Reporting Services will try to get the image using anonymous access. http://technet.microsoft.com/en-us/library/dd220527.aspx A: Ok, I got it figured out. What I did was in the image properties, in the General Tab, I selected the image source as External, I then created a report parameter Called "@ImageURL", and selected it in the "Use this image:". On the form I added this line of code: ReportViewer1.LocalReport.SetParameters(New Parameter("ImageURL", string.concat("file:\","C:\ImagesFolder\ImageName.jpg"))) this brings up the image correctly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571429", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: LLVM complains about assembler error "Unexpected token in memory operand" I'm doing a study assignment to measure memory access time on my machine. To determine the clock cycles on our machines, we have been given the following C snippet: static inline void getcyclecount(uint64_t* cycles) { __asm __volatile( "cpuid # force all previous instruction to complete\n\t" "rdtsc # TSC -> edx:eax \n\t" "movl %%edx, 4(0) # store edx\n\t" "movl %%eax, 0(0) # store eax\n\t" : : "r"(cycles) : "eax", "ebx", "ecx", "edx"); } However, when I try to compile this (XCode 4, using "Apple LLVM Compiler 2.1"), it results twice in the error "Unexpected token in memory operand" at the "\t" of the rdtsc resp. first movl instruction line. I know basic assembler, but have no clue about the C inline assembler format. Does anyone of you know what could be the issue with this code? Thanks! A: Assuming this is GCC inline assembly syntax, you're missing a % in the memory operand: __asm __volatile( "cpuid # force all previous instruction to complete\n\t" "rdtsc # TSC -> edx:eax \n\t" "movl %%edx, 4(%0) # store edx\n\t" "movl %%eax, 0(%0) # store eax\n\t" : : "r"(cycles) : "eax", "ebx", "ecx", "edx");
{ "language": "en", "url": "https://stackoverflow.com/questions/7571433", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Stop unBound service in Android I have a service that autoupdates a database in a given time interval. To do this it gets information from the Internet. I need to have it unbound, so that It runs over all activities. But when the application is closed, it would be nice to terminate the service. To prevent battery drain. How can this be achieved? A: I think that you should let your service be started by a boot broadcastReceiver, then ask AlarmManager to relaunch it every now and then. public class DbUpdateService extends Service { //compat to support older devices @Override public void onStart(Intent intent, int startId) { onStartCommand(intent, 0, startId); } @Override public int onStartCommand (Intent intent, int flags, int startId){ //your method to update the database UpdateTheDatabaseOnceNow(); //reschedule me to check again tomorrow Intent serviceIntent = new Intent(DbUpdateService.this,DbUpdateService.class); PendingIntent restartServiceIntent = PendingIntent.getService(DbUpdateService.this, 0, serviceIntent,0); AlarmManager alarms = (AlarmManager)getSystemService(ALARM_SERVICE); // cancel previous alarm alarms.cancel(restartServiceIntent); // schedule alarm for today + 1 day Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DATE, 1); // schedule the alarm alarms.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), restartServiceIntent); return Service.START_STICKY; } } To start your service at boot time use this : import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class serviceAutoLauncher extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { Intent serviceIntent = new Intent(context,DbUpdateService.class); context.startService(serviceIntent); } } Finally add this to your manifest to schedule your serviceAutoLauncher to be launched at each boot: <receiver android:name="serviceAutoLauncher"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED"></action> <category android:name="android.intent.category.HOME"></category> </intent-filter> </receiver> A: Use the stopService method. A: It depends on how you start the service. If you start it when your Activity is opened, then call stopService in your Activities onDestroy().
{ "language": "en", "url": "https://stackoverflow.com/questions/7571438", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I use the Inversion of Control concept in Sitecore to get non-page items to display themselves? I have a number of non-page content items that are used as "callouts" on the side of pages throughout my website that I am building in Sitecore. Ideally I would like to be able to define the presentation information for these callouts independently. Then when a CMS author selects callouts for a particular page in the site, they know how to display themselves. I read an excellent blog post about how to do this here: http://www.awareweb.com/AwareBlog/InversionControl2.aspx. I used the first method that he describes in the post. However my implementation of that code doesn't completely work. It seems to get the correct rendering and it iterates properly through the selected non-page callout items. But when it displays them on the page it seems like the callout items are still using Sitecore.Context.Item as their source item and not the source item that was passed in to them via the strDataSource variable as seen in the example code. Do I have to do anything special in the code behind for the sublayouts for the callouts to tell them not to use Sitecore.Context.Item and instead to use the source item that was passed in? Otherwise I can't figure out why it's not working. Any ideas? Thanks, Corey A: Setting the DataSource in a sublayout doesn't explicitly set the Context.Item to a different value, it just sets a property in a sublayout that it can use itself. Rather than write up the solution again, John West's blog already covers this subject here, so I'd recommend you read that - http://www.sitecore.net/Community/Technical-Blogs/John-West-Sitecore-Blog/Posts/2010/11/How-to-Apply-Data-Sources-to-Sitecore-ASPNET-Presentation-Components.aspx I would recommend using the SublayoutParameterHelper Shared Source library which provides a Helper and a base class to use with your sublayouts for accessing the Item represented by an ID set in the DataSource; John also cites this library in his blog post.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571450", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: E-mail all - Character limit issue Is there anyway to get around the maximum character limit on "mailto:"? the requirement is to have an option send email to all the persons returned by search criteria. So, on the controller side, after the person objects are gathered, I have iterated through them all to get a "To" string with all their emailids appended. But the issue is that, on the view side <a href="mailTo:${toList}">Email all Returned results</a> won't work when the toList size exceeds certain limit(2083 for IE, apparently). So is there anyway to get around this limit? My requirement is not to send email to the results, just open up the e-mail client for users and they can decide what to have in body and whom to remove from the list etc.. A: First off, there's no way to "get around" that IE limit (more info here: http://support.microsoft.com/kb/208427 ). If you really need to send so much emails at once switch to a server-side solution (and it will be far better even for the privacy) OR just ask the users to use another browser.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571466", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Class not found javax.persistence.EntityNotFoundException I have problem with creating executable jar file. I creating the jar file by Intellij idea X artifacts. But when I try to execute this jar, it gave me an error: Exception in thread "main" java.lang.NoClassDefFoundError: javax/persistence/EntityNotFoundException Caused by: java.lang.ClassNotFoundException: javax.persistence.EntityNotFoundException at java.net.URLClassLoader$1.run(URLClassLoader.java:202) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:190) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at java.lang.ClassLoader.loadClass(ClassLoader.java:247) I check which package contains this class and I found it in this maven dependency: <dependency> <groupId>org.hibernate.javax.persistence</groupId> <artifactId>hibernate-jpa-2.0-api</artifactId> </dependency> I check if the Intellij add this jar to my executable jar and I found it there. So have someone any Idea where the problem is? A: Try adding: javaee-api-5.0-2.jar to your project. A: Indeed, hibernate-jpa-2.0-api contains this class. It might be a classpath issue. Are you including required jar libraries in your jar? Can your app access other application provided jars at runtime? You may find the answers to this question useful: Classpath including JAR within a JAR A: The JPA libs are a separate external download from Oracle. You may need to download them separately and install them into your local Maven repo. You should also be specifying a version in your dependency XML.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571467", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: UIDatePicker without "hour" label UIDatePicker in CountDownTimer mode shows the labels like this : 4 hours | 12 mins How can you customize to look like this : 4 | 12 mins ? Thanks A: UIDatePicker does not allow this. You could conceivably create your own date picker using a specialized UIPickerView and do it that way, but it'd be a fair amount of work. If you'd like this ability on UIDatePicker, please file a bug requesting it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571474", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Open Graph Beta: define action, object, and publishing I'm trying to learn and test out the new open graph beta that allows you to define actions, objects, and publish them. I believe I'm following the tutorial and doing exactly what it says, but the defined actions are not publishing. I would greatly appreciate it if someone could help me discover what I'm doing wrong. Here's the details: For the object, here's what I get when I click get code: (I'm changing header links since I can't post more than 2 links on my account) <head prefix="og: htp://ogp.me/ns# fb: http://ogp.me/ns/fb# bible_app: http://ogp.me/ns/fb/bible_app#"> <meta property="fb:app_id" content="223527597700292"> <meta property="og:type" content="bible_app:verse"> <meta property="og:url" content="Put Your Own URL Here"> <meta property="og:title" content="Sample Verse"> <meta property="og:description" content="Some Arbitrary String"> <meta property="og:image" content="https://s- static.ak.fbcdn.net/images/devsite/attachment_blank.png"> For og:url, I have tried the actual page where I have the object: bibleverses4.me/app/learn.html and I've also tried the sample url samples.ogp.me/225426837510368. For the action, I just modified the tutorial: `FB.api('/me/bible_app:learn' + '?learn=http://bibleverse4.me/app/learn.html','post', function(response)` For the url in the action, I have tried both the above url and the sample FB gives. The end result and problem: everything shows up, but when I click the "Learn" button, it says The page at Bibleverses4.me says: Error occured So, I'm guessing I'm doing something wrong here, but I'm trying to learn and would greatly appreciate any help that could be offered. Thanks. A: I think that it should be: FB.api('/me/bible_app:learn' + '?verse=http://bibleverse4.me/app/learn.html','post', function(response) Where the /me/bible_app:learn is your action and verse is your object...
{ "language": "en", "url": "https://stackoverflow.com/questions/7571481", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android Sha1 Hash username and password not hashing correctly I have a little problem with hashing a username and password.I need to find a way to hash the data with java as the server did with mysql.Here is a mysql hashing : and I'm trying to get the same result in Java like this : String userName_input = txtUserName.getText().toString(); String password_input = txtPassword.getText().toString(); try { String userName_hash; String password_hash; String username = SHA1.Sha1Hash(userName_input); String password = SHA1.Sha1Hash(password_input); String username1 = SHA1.Sha1Hash((username.concat(password)).substring(20, 35)); String password1 = SHA1.Sha1Hash((password.concat(username)).substring(10, 35)); userName_hash = SHA1.Sha1Hash(username1.concat(username)); password_hash = SHA1.Sha1Hash(password1.concat(password)); //THE RESULT WHICH SERVER RETURNS AND THE RESULT OF JAVA HASH UsernameHash (fcd86e8cc9fc7596f102de7b2b922e80c6e6fac9) : dd1ed59ebab6c420d750046539fcb60e7a1f9162 PasswordHash (b66936348bd0bd44fa44f5ca7dcceb909545e47f) : cde70a6416e061d00b4247b73c54c73fee7116ab But the result that I get is not the same as in mysql hash.I'm using this SHA1 code : public class SHA1 { private static String convertToHex(byte[] data) { StringBuffer buf = new StringBuffer(); for (int i = 0; i < data.length; i++) { int halfbyte = (data[i] >>> 4) & 0x0F; int two_halfs = 0; do { if ((0 <= halfbyte) && (halfbyte <= 9)) buf.append((char) ('0' + halfbyte)); else buf.append((char) ('a' + (halfbyte - 10))); halfbyte = data[i] & 0x0F; } while(two_halfs++ < 1); } return buf.toString(); } public static String Sha1Hash(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); } } Any ideas/suggestions where is my mistake and how to get the hashing work exactly as in mysql? Thanks in advance!!! A: Depending on the source that you give this should work properly : String hashUser = SHA1.Sha1Hash(username); String hashPass = SHA1.Sha1Hash(password); /** * HASH USERNAME * sha1(concat(sha1(substr(concat(sha1('username'),sha1('password')),20,35)),sha1('username'))) */ String userPLUSpass = hashUser+hashPass; String userConcat = ""; String subStringUserHash = userConcat.concat(userPLUSpass); String userHashSubStr = SHA1.Sha1Hash(subStringUserHash.substring(19, 54)); String luser = userHashSubStr+hashUser; String uConcat = ""; lastUser = SHA1.Sha1Hash(uConcat.concat(luser)); /** * HASH PASSWORD * sha1(concat(sha1(substr(concat(sha1('password'),sha1('username')),10,35)),sha1('password'))) */ String passPLUSuser = hashPass+hashUser; String passConcat = ""; String subStringPassHash = passConcat.concat(passPLUSuser); String passHashSubStr = SHA1.Sha1Hash(subStringPassHash.substring(9, 44)); String lpass = passHashSubStr+hashPass; String pConcat = ""; lastPass = SHA1.Sha1Hash(pConcat.concat(lpass));
{ "language": "en", "url": "https://stackoverflow.com/questions/7571485", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to post an array of files in ASP.NET MVC 3? I would like to be able to post multiple files in one form. I would like to pass these files as an array of files. For example I would like to do this. <input type="file" name="files[0]" /> <input type="file" name="files[1]" /> <input type="file" name="files[2]" /> Then I would like to be able to receive these files as an array in the Controller. I've tried this. public ActionResult AddPart(HttpPostedFileBase[] files) But that doesn't work. I've googled it but all I can find is examples on uploading one file. Does anyone know how to do this using MVC3 C#. A: If you want to upload not only one file, you need to use enctype="multipart/form-data" in your form. @using (Html.BeginForm("", "Client", FormMethod.Post, new {enctype="multipart/form-data"})) And controller: [HttpPost] public ActionResult AddPart(IEnumerable<HttpPostedFileBase> files) All other parts is ok. A: Well i got almost a same case. But that is for nested array of files. using IEnumerable as an array([ ]) solved my problem. [] s [HttpPost] public ActionResult AddPart(IEnumerable<HttpPostedFileBase>[] files)
{ "language": "en", "url": "https://stackoverflow.com/questions/7571488", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: CSS not appearing correctly in IE9 On my website the css is not appearing correctly only in IE9. IE8, Chrome and firefox appear just fine. Any help much appreciated! Website: http://www.victoryit.com/ A: You are using cufon 1.09. There is a bug in this version which causes the fonts to disappear in IE9. Please upgrade to version 1.10. Edit: Use 1.09i as 1.10 has not been released yet.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Showing/hiding content from FB fans on my own site So I'm adding the 'like' button to my site and I've got it to display "Thank you for liking example.com" and "You seemed to have unliked example.com" using edge.create; FB.Event.subscribe('edge.create', function(response) { document.getElementById("demo").innerHTML=('Thank you for liking example.com'); } ); FB.Event.subscribe('edge.remove', function(response) { document.getElementById("demo").innerHTML=('You seemed to have unliked example.com'); } ); However this method only works when the button is clicked. If a visitor comes to my site and has already liked example.com I would like to show them a message without them having to click anything. I know this is possible to do on a facebook page but what about on my own site. Any ideas? Cheers A: Certainly possible using FB.getLoginStatus FB.getLoginStatus(function(response) { if (response.authResponse) { // logged in and connected user, someone you know } else { // no user session available, someone you dont know } }); http://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/ Keep in mind that this refers to a user being logged in to your app and / or Facebook. If someone is not logged in to Facebook, they will of course return FALSE and thus your message should reflect to have them connect OR login.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571499", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to implode and keep value for each link? Say I have the following code: $arr = array('id' => $tarr = array('1' => 'Fred', '2' => 'Wilma', 'c' => 'Bam Bam')); echo '<a href="?tag='.$tarr.'">' . implode( '</a>, <a href="?tag='.$tarr.'">', $tarr) . '</a>'; This displays: Fred, Wilma, Bam Bam but the href shows value Array instead of Fred for Fred, Wilma for Wilma etc Cheers A: You can build an output string (or array as shown here) using a foreach loop: foreach($tarr as $v){ $out[] = "<a href='?tag=$v'>$v</a>"; } echo implode(', ', $out) A: I think what youy are trying to do is this: $arr = array('1' => 'Fred', '2' => 'Wilma', 'c' => 'Bam Bam'); echo '<a href="?tag='.implode('"></a><a href="?tag=',$arr).'"></a>'; A: $tarr is an array, so when it's converted to a string, it prints Array. Don't use implode here, you should use a for loop to get each value of the array. What you should do is something like this: $tarr = array('1' => 'Fred', '2' => 'Wilma', 'c' => 'Bam Bam'); $aTags = array(); foreach($tarr as $v){ $aTags[] = '<a href="?tag='.$v.'">'.$v.'</a>'; } echo implode(', ', $aTags); Also, why do you have $arr here? It's totally useless. $arr = array('id' => $tarr = array('1' => 'Fred', '2' => 'Wilma', 'c' => 'Bam Bam')); This is the same as: $tarr = array('1' => 'Fred', '2' => 'Wilma', 'c' => 'Bam Bam'); $arr = array('id' => $tarr);
{ "language": "en", "url": "https://stackoverflow.com/questions/7571500", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: String.StartsWith does not work as I expect string word1 = ""; //see example string word2 = ""; bool b1 = word1.StartsWith(word2); bool b2 = word1.Substring(0, word2.Length) == word2; for some Arabic strings b1 does not equal b2? Could you explain this behavior? Example: word1 = ((char)0x0650).ToString()+ ((char)0x0652).ToString()+ ((char)0x064e).ToString(); word2 = ((char)0x0650).ToString()+ ((char)0x0652).ToString(); A: There is a difference: .StartsWith performs a culture sensitive comparison, while .Equals (what you use with ==) doesn't. So if you have two strings, that are different when you compare them character-by-character (== returns false), but are considered equal by your culture (startswith returns true), you could get this result. EDIT If I try your example values with this: bool b1 = word1.StartsWith(word2, StringComparison.Ordinal); bool b2 = word1.Substring(0, word2.Length).Equals(word2, StringComparison.Ordinal); both return "True".
{ "language": "en", "url": "https://stackoverflow.com/questions/7571503", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Mocking NetworkStream with MemoryStream for Unit Testing I have a class that is wrapping a stream, with the intention of that stream likely being a NetworkStream. However in unit testing it is much easier to use a MemoryStream to verify functionality. However I have noticed that MemoryStream and NetworkStream don't actually act the same on write. When I write to a MemoryStream the seek pointer of the stream is set to the end of what I wrote. In order to read out what I wrote I have to adjust the Seek pointer back to the beginning of what I wrote. When I write to a NetworkStream the other end of the stream can read that data without adjusting the seek pointer. I assume that a NetworkStream is handling the concept of the seek pointer internally and making sure that even though it is filling data into the stream on the other side it is not adjusting the pointer. My question then is, what is the best way to mock that same behavior in the MemoryStream? I thought I might just seek the pointer back the same number of bytes I write but that seems cludgy. Also If I stack several of these streams together or other wrapped streams, how will they know whether the pointer needs reset or not? A: MemoryStream isn't designed for how you are using it. A NetworkStream is designed to allow you to fill up a block of memory with your output. It is not designed to have a second object reading from what the original object is writing. I would suggest that you create a FakeNetworkStream class. You would have two objects, writing to one would add data to the other. But the advantage of a FakeNetworkStream is that you can implement pathological socket behavior to detect as many bugs as possible. * *Don't send any data until the user flushes the stream. Subtle bugs can arise when a socket is not flushed because where or not the data is actually sent can vary. By always waiting until the flush you can have your tests fail when a flush actually need to happen. *Read isn't guaranteed to produce all of the data you request. Simulate this by only ever producing a single byte at a time. A: This might help. https://github.com/billpg/POP3Listener/commit/a73a325f21a955edd9f1023a94c586aba29cfadc#diff-80d1609ed97fdaa9538dea7547301577cc19b6f4466a1a0a3a0ac08ad3eea23e This function returns two NetworkStream objects, a client and a server, by briefly opening a server, connecting to that server, and returning both ends.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571504", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to suppress SLF4J Warning about multiple bindings? My java project has dependencies with different SLF4J versions. How do I suppress the annoying warnings? SLF4J: Class path contains multiple SLF4J bindings. SLF4J: Found binding in [jar:file:xyz234/lib/slf4j- log4j12-1.5.8.jar!/org/slf4j/impl/StaticLoggerBinder.class] SLF4J: Found binding in [jar:file:xyz123/.m2/repository/org/slf4j/slf4j-log4j12 /1.6.0/slf4j-log4j12-1.6.0.jar!/org/slf4j/impl/StaticLoggerBinder.class] SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation. P.S.: This is not the same question as slf4j warning about the same binding being duplicate, the answer there is how to get rid of a false alarm warning, in my case it is a true warning however. P.S.S.: Sorry, I forgot to mention: I use Maven and SLF4J is included in the dependencies of my dependencies. A: PrintStream filterOut = new PrintStream(System.err) { public void println(String l) { if (! l.startsWith("SLF4J")) { super.println(l); } } }; System.setErr(filterOut); et voilà! A: Have you read the URL referenced by the warning? SLF4J: See [http://www.slf4j.org/codes.html#multiple_bindings][1] for an explanation. Here is what the link states: SLF4J API is desinged to bind with one and only one underlying logging framework at a time. If more than one binding is present on the class path, SLF4J will emit a warning, listing the location of those bindings. When this happens, select the one and only one binding you wish to use, and remove the other bindings. For example, if you have both slf4j-simple-1.6.2.jar and slf4j-nop-1.6.2.jar on the class path and you wish to use the nop (no-operation) binding, then remove slf4j-simple-1.6.2.jar from the class path. Note that the warning emitted by SLF4J is just that, a warning. SLF4J will still bind with the first framework it finds on the class path. A: Remove one of the slf4j-log4j12-1.5.8.jar or slf4j-log4j12-1.6.0.jar from the classpath. Your project should not depend on different versions of SLF4J. I suggest you to use just the 1.6.0. If you're using Maven, you can exclude transitive dependencies. Here is an example: <dependency> <groupId>com.sun.xml.stream</groupId> <artifactId>sjsxp</artifactId> <version>1.0.1</version> <exclusions> <exclusion> <groupId>javax.xml.stream</groupId> <artifactId>stax-api</artifactId> </exclusion> </exclusions> </dependency> With the current slf4j-api implementation it is not possible to remove these warnings. The org.slf4j.LoggerFactory class prints the messages: ... if (implementationSet.size() > 1) { Util.report("Class path contains multiple SLF4J bindings."); Iterator iterator = implementationSet.iterator(); while(iterator.hasNext()) { URL path = (URL) iterator.next(); Util.report("Found binding in [" + path + "]"); } Util.report("See " + MULTIPLE_BINDINGS_URL + " for an explanation."); } ... The Util class is the following: public class Util { static final public void report(String msg, Throwable t) { System.err.println(msg); System.err.println("Reported exception:"); t.printStackTrace(); } ... The report method writes directly to System.err. A workaround could be to replace the System.err with System.setErr() before the first LoggerFactory.getLogger() call but you could lose other important messages if you do that. Of course you can download the source and remove these Util.report calls and use your modified slf4j-api in your project. A: If using maven always use the command mvn dependency:tree This will list all the dependencies added to the project including dependencies to the jars we have included. Here we can pin point multiple version, or multiple copies of jars that come in with other jars which were added. Use <exclusions><exclusion><groupId></groupId><artifactId></artifactId></exclusion></exclusions> in <dependency> element to exclude the ones which conflict. Always re-run the maven command above after each exclusion if the issue persist. A: Sometimes excluding the 2nd logger from the classpath would require too many contortions, and the warning is incredibly annoying. Masking out the standard error as the very beginning of the program does seem to work, e.g. public static void main(String[] args) { org.apache.log4j.Logger.getRootLogger().setLevel(org.apache.log4j.Level.OFF); PrintStream old = System.err; System.setErr(new PrintStream(new ByteArrayOutputStream())); // ... trigger it ... System.setErr(old); ... whereby the trigger it part should call some nop function that accesses the logging system and would have otherwise caused the message to be generated. I wouldn't recommend this for production code, but for skunkworks purposes it should help. A: If you're using an old version of Jetty (say Jetty 6), you may need to change the classloading order for the webapp to make it higher priority than the container's. You can do that by adding this line to the container's xml file: <Set name="parentLoaderPriority">false</Set>
{ "language": "en", "url": "https://stackoverflow.com/questions/7571506", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: How to stop repetition in my code? * *This code executes primes upto a given number. It works correctly as far as the prime generation is concerned but the output is painfully repetitive. *The code is: numP = 1 x = 3 y = int(input('Enter number of primes to be found: ')) while numP<=y: for n in range(2, x): for b in range(2, n): if n % b == 0: break else: # loop fell through without finding a factor print (n) x += 2 numP += 1 *The output is like (e.g. for y=4): 2 2 3 2 3 5 2 3 5 7 *I want to avoid repetition and obtain output like: 2 3 5 7 *How should the code be modified? A: If you store the data in a set, you will avoid repetitions A: There's no reason to loop n from 2..x. Get rid of that loop, and replace all references to 'n' with 'x'. I.e.: def find_primes(y): x = 3 numP = 0 while True: for b in range(2, x): if x % b == 0: break else: # loop fell through without finding a factor print (x) numP += 1 if numP >= y: return x += 2
{ "language": "en", "url": "https://stackoverflow.com/questions/7571509", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problem with Encapsulation in C# (inaccesible due to protection level) I am very new to C# and am stumbling through. I understand the need for encapsulation but whenever I break a working application into diffrent classes I always have problems. I have written a simple program that allows a user to click checkboxes on an inventory list. The items are shown in a textbox and the contents of the textbox are emailed to a pre-defined address when a submit button is clicked. The line... oMsg.Body = Form1.textBox1.text Gives me the Error: "MY_App.Form1.textBox1.text is inaccesible due to its protection level". Form1 and Class1 are as follows... namespace MY_App { public partial class Form1 : Form { public Form1() { InitializeComponent(); } List<string> ls = new List<string>(); private void Checkbox1_CheckedChanged(object sender, EventArgs e) { ls.Add( "P.C. "); } private void Checkbox2_CheckedChanged(object sender, EventArgs e) { ls.Add( "WYSE Terminal" ); } private void Checkbox3_CheckedChanged(object sender, EventArgs e) { ls.Add("Dual Monitors "); } public void button1_Click(object sender, EventArgs e) { InputText(); Class1.SendMail(textBox1.Text); } public void textBox1_TextChanged(object sender, EventArgs e) { } public void InputText() { string line = string.Join(",", ls.ToArray()); textBoxTEST.AppendText(line); } And then the Emailing class (Class1)… using System; using Outlook = Microsoft.Office.Interop.Outlook; namespace MY_App { public class Class1: Form1 { public void SendMail(string[] args) { try { Outlook.Application oApp = new Outlook.Application(); Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem (Outlook.OlItemType.olMailItem); Outlook.Recipient oRecip = (Outlook.Recipient)oMsg.Recipients.Add("email@gmail.com"); oRecip.Resolve(); oMsg.Subject = "Deskstop Standards: Required Items"; oMsg.Body = Form1.textBox1.text oMsg.Display(true); oMsg.Save(); oMsg.Send(); oRecip = null; oMsg = null; oApp = null; } catch (Exception e) { Console.WriteLine("{problem with email execution} Exception caught: ", e); } return; } } } I relize this is a ton of code but I don't know where to isulate the problem. Also, I greatly appreciate any help but if anyone could explain the answer as well so I don't continue writing bad code I truely would appreciate it. Thanks in advance. A: There are a couple of problems here. The first is you are trying to have Class1 inherit from Form1, but you want to use the values from an instance of Form1 inside an instance of Class1, rather than from the instance of Class1. Let me see if I can explain this using your code names. Suppose you have a builder that builds homes using prebuilt parts (ie, the house is shipped to you whole). He has a base house called Form, a more specific house design called Form1 that is based on Form and an even more specific design Class1 that is based on Form1. Your neighbor buys a Form1 house and you buy a Class1 house. you each have a mailbox called a TextBox1. You are at your house and want to read your neighbors mail out of his textbox1. Since your neighbor is down the street, this is impossible. A bit convoluted? Sure. For proper design of your application, Form1 inheriting from Form is correct. Class1 inheriting from Form1 is not, unless Class1 is going to actually be a Form in the application. If it is a mail sender, you should create a class more like this: public class Class1 { public void SendMail(string args) { try { var oApp = new Outlook.Application(); var oMsg = (Outlook.MailItem) oApp.CreateItem(Outlook.OlItemType.olMailItem); var oRecip = (Outlook.Recipient) oMsg.Recipients.Add("email@gmail.com"); oRecip.Resolve(); oMsg.Subject = "Deskstop Standards: Required Items"; oMsg.Body = body oMsg.Display(true); oMsg.Save(); oMsg.Send(); oRecip = null; oMsg = null; oApp = null; } catch (Exception e) { Console.WriteLine("{problem with email execution} Exception caught: ", e); } return; } } i would actually use System.Net.Mail instead of Outlook, but that is another lesson. To call this, you use the following from Form1: Class1 mailer = new Class1(); mailer.SendMail("This is my body message"); A: As long as Class1 is inherited from Form1 and text box access modifier is protected you can simply access it: oMsg.Body = this.textBox1.text; If textBox is private - expose a wrapper for the textbox Text property and then use it: public partial class Form1 { public string TextWrapper { get { return this.textBox.Text; } set { this.textBox.Text = value; } } And use it: oMsg.Body = this.TextWrapper; PS: your original code looks wrong to me because you'are accessing textbox as type member of Form1 class, basically like a static variable.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571510", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery Ajax and AddThis social bookmark application I am developing a website that has an AddThis Integration Here's my situation right now, Every time a user inputs an RSS Feed in a text input, it will display the results in the same page since I'm using an AJAX on fetching the data. Together with the result is the AddThis code that has javascripts in it. My problem here is the AddThis button is not appearing when I started using AJAX. But before using that one, it works perfectly. Here's the code. <div id="entry-form"> <table> <tr> <td>Insert RSS Feed Here:</td> <td><input type="text" name="url" id="url" style='width:300px;' /></td> </tr> </table> <input type='button' name='submit' value='Submit' class='submit' /> <div class='urlResult' style='background-color:white; width:75%;'></div> </div> When the user clicks on the button it runs on this jQuery script: jQuery('.submit').click(function() { if( jQuery('#url').val() == "" ) return false; jQuery.ajax({ type: "POST", url: "parse.php", data: "url="+jQuery('#url').val(), success: function(data) { jQuery(".urlResult").html(data); } }); }); This is the parse.php file/code: <?php $file = $_POST['url']; $xml = simplexml_load_file($file,'SimpleXMLElement',LIBXML_NOCDATA); foreach($xml as $key) { $links = $key->item; for($x=0; $x<count($links); $x++) { echo "<pre>"; echo $links[$x]->link; echo "</pre>"; ?> <!-- AddThis Button BEGIN --> <div class="addthis_toolbox addthis_default_style "> <a class="addthis_button_preferred_1"></a> <a class="addthis_button_preferred_2"></a> <a class="addthis_button_preferred_3"></a> <a class="addthis_button_preferred_4"></a> <a class="addthis_button_compact"></a> <a class="addthis_counter addthis_bubble_style"></a> </div> <script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#pubid=xa-4e6622545c73a715"></script> <!-- AddThis Button END --> <?php } } ?> The problem here is that this code is not appearing since I started to use jquery-ajax: This code allows the display of the addThis buttons. <div class="addthis_toolbox addthis_default_style "> <a class="addthis_button_preferred_1"></a> <a class="addthis_button_preferred_2"></a> <a class="addthis_button_preferred_3"></a> <a class="addthis_button_preferred_4"></a> <a class="addthis_button_compact"></a> <a class="addthis_counter addthis_bubble_style"></a> </div> <script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#pubid=xa-4e6622545c73a715"></script> The javascript files that were embedded on my site is only the jQuery script. A: This post solved my issue -- you need to dynamically load in the script via $.getScript(): http://kb.jaxara.com/how-initialize-addthis-social-sharing-widgets-loaded-ajax
{ "language": "en", "url": "https://stackoverflow.com/questions/7571515", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to reveal text line by line - Xcode I have a simple app, I have a button that when pressed will display separate lines of text on the screen. I set an int = 0 and use an if statement that will add 1 at each line. The issue I have is that all lines are displayed after 1 button press, I want 1 button press one line displayed, next button press next line displayed and so on: int nmbr = 0; int myInt1 = [textfield.text intValue]; if (nmbr == 0) { tString = [[NSString alloc] initWithFormat:@"111111111111%i x 1 = %i",myInt1,myInt1]; nmbr++; } if (nmbr == 1){ tString1 = [[NSString alloc] initWithFormat:@"222222222222%i x 2 = %i",myInt1,myInt1*2]; nmbr++; } if (nmbr == 2){ tString2 = [[NSString alloc] initWithFormat:@"%i x 3 = %i",myInt1,myInt1*3]; nmbr++; } I am new to this so any help is greatly appreciated. Update: Thanks folks for your help so far, I am not sure that I have explained this issue well……possibly gone about programming it all wrong. I have only one button on screen and each time it is pressed it would change a blank label to a text string. I was incrementing in each if statement so that on the next button press as nmbr = 2 then text label 2 would be modified, press again nmbr = 3 text label 3 would be modified and so on. There appears to be no separation in the code so on the button press all text labels are modified. I am not sure if it is possible to code multiple actions on a single button or if there is a better way to do this. I have tried else if statements but still no joy. A: Move your nmbr++; to the end of the method instead of putting it in each if statement. If you don't want it to increment every time then use a bool to keep track of whether or not you want to increment it. Also, nmbr needs to be a member variable (i.e. class level) instead of method level. If it is method level then its state isn't saved between calls. A: Your result is normal because you if test are coming one after each other. The program will go on the first if, incremented nmbr, go out of the if and hit the next if. It can work by moving the nmbr incrementation out of the "if" (as mentioned by mydogisbox) but you will still have to declare the variable as static. Something like this: static int nmbr = 0; int myInt1 = [textfield.text intValue]; if (nmbr == 0) { tString = [[NSString alloc] initWithFormat:@"111111111111%i x 1 = %i",myInt1,myInt1]; } if (nmbr == 1){ tString1 = [[NSString alloc] initWithFormat:@"222222222222%i x 2 = %i",myInt1,myInt1*2]; } if (nmbr == 2){ tString2 = [[NSString alloc] initWithFormat:@"%i x 3 = %i",myInt1,myInt1*3]; nmbr = 0; // if you have no other lines and you want to start from begining when the user press the button more than 3 times. } nmbr++; A: Create required number of buttons in Interface Builder, declare them into .h file, create methods for each button -(void)firstButtonClick:(UIButton)sender, -(void)secondButtonClick:(UIButton)sender and put your code into these methods. A: The problem is that you're incrementing within the if and then letting it fall to the next. Look at the flow: nmbr is one, so execute that block, which increments nmber to 1, making the next block true also. Depending on your style guides or personal preferences, you could: * *Change the later ifs to else if. *Move all the nmbr++s to after the last if. *Return after incrementing inside the if.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571518", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: One-row subgrids not expanding I have a grid where each row has a subgrid. It seems that when a subgrid has multiple rows, it is expandable. But when it has only one row, it is not expandable. How can a row that contains a one-row subgrid be made to be expandable? I am using the "grid as a sub-grid" method for displaying subgrids. A: I was using a special character "$" in the sub-grid's ID.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571519", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sending a parameter to the controller in ASP MVC 2 I am writing an area for administering several subsites, almost all of the functionality will be the same across each site (add/edit/remove pages etc) and my repository on instantiation takes the SiteIdentity so all the data access methods are agnostic in relation to this. The problem I have at the moment is trying to make my action methods also agnostic. The URL pattern I want to use is along the lines of: "ExternalSite/{identity}/{controller}/{action}/{id}" A naive approach is to have each action take the identity parameter, but this means having to pass this in to my repository on each action as well as include it in the ViewData for a couple of UI elements. I'd much rather have this something that happens once in the controller, such as in its constructor. What is the best way to do this? Currently the best I can come up with is trying to find and cast identity from the RouteData dictionary but part of me feels like there should be a more elegant solution. A: You have access to your route values in Request.RequestContext.RouteData, so you can make base controller and public property SiteIdentity, in such case you can access it from all actions in all inherited controllers. A: It sounds like you want to use OnActionExecuting or a Custom ModelBinder to do that logic each time you have a specific parameter name (also known as a RouteData dictionary key). * *Creating a custom modelbinder in ASP.NET MVC *Creating an OnActionExecuting method in ASP.NET MVC, Doing Serverside tracking in ASP.NET MVC
{ "language": "en", "url": "https://stackoverflow.com/questions/7571523", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: On Android, How can I get a small .png to appear where I tapped with my finger with the camera active Thanks in advance for your time! This has been bothering me for quite some time now. What I want is to display a small .png image on the screen where I tapped my finger, with the camera being active. I don't want any picture to be taken or anything, I only want it to display what the camera sees and on top of that, a small .png file. I'm trying to make a geographic game where you are able to "shoot" your opponent in the end by seeing through the camera, and tapping him on the screen, to shoot him. I'm kind of new at this, so the code I made is useless, for anybody, me included :S Any help or advice is much appreciated:) A: To make this effect, first of all you can't use the default Camera App, like this: Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); because you can't modify anything on this activity. And actuary you can write an activity use hardware.camera to take picture. http://developer.android.com/reference/android/hardware/Camera.html This will need some knowledge about SurfaceView to show the camera preview and the small .png images, but I'm sure you will find a lot of examples around the Internet.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571525", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error Nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException WebFlow I have a error like this working with webflow 2.3.0.RELEASE and richfaces 4.0.0.Final in jboss 7.0.1.FINAL: 12:16:46,989 INFO [stdout] (MSC service thread 1-7) 2011-09-20 12:16:46,987 [MSC service thread 1-7] ERROR (FrameworkServlet.java:314) � Context initialization failed 12:16:46,989 INFO [stdout] (MSC service thread 1-7) org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flowExecutor': Cannot create inner bean '(inner bean)' of type [org.springframework.webflow.config.FlowExecutionListenerLoaderFactoryBean] while setting bean property 'flowExecutionListenerLoader'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#1':Cannot resolve reference to bean 'jpaFlowExecutionListener' while setting bean property 'listeners'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaFlowExecutionListener' defined in ServletContext resource [/WEB-INF/spring/transportes-webflow.xml]: Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' is defined. Well I suppose that the error is because I have the Hibernate configuracion in META-INF like this: * *META-INF/spring/spring-master.xml * *META-INF/spring/spring-hibernate.xml *META-INF/spring/spring-datasource.xml *META-INF/spring/jdbc.properties and the webflow configuration in WEB-INF: WEB-INF/spring/transportes-webflow.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:webflow="http://www.springframework.org/schema/webflow-config" xmlns:context="http://www.springframework.org/schema/context" xmlns:faces="http://www.springframework.org/schema/faces" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/webflow-config http://www.springframework.org/schema/webflow-config/spring-webflow-config-2.3.xsd http://www.springframework.org/schema/faces http://www.springframework.org/schema/faces/spring-faces-2.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!--Flow executor for Jpa integration and security --> <webflow:flow-executor id="flowExecutor"> <webflow:flow-execution-listeners> <webflow:listener ref="securityFlowExecutionListener"/> <webflow:listener ref="jpaFlowExecutionListener"/> </webflow:flow-execution-listeners> </webflow:flow-executor> <!-- Flow register --> <webflow:flow-registry flow-builder-services="facesFlowBuilderServices" id="flowRegistry" base-path="/WEB-INF/flows/"> <!-- <webflow:flow-location path="/welcome/welcome.xml"/> --> <webflow:flow-location-pattern value="/**/*-flow.xml"/> </webflow:flow-registry> <faces:flow-builder-services id="facesFlowBuilderServices" enable-managed-beans="true" development="true"/> <!-- For use interface flow controller --> <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/> <bean class="org.springframework.webflow.mvc.servlet.FlowHandlerAdapter"> <property name="flowExecutor" ref="flowExecutor"/> <!-- need to tell Spring Web Flow about how to handle Ajax requests. --> <property name="ajaxHandler"> <bean class="org.springframework.faces.richfaces.RichFacesAjaxHandler" /> </property> </bean> <bean class="org.springframework.webflow.mvc.servlet.FlowHandlerMapping"> <property name="flowRegistry" ref="flowRegistry"/> <property name="defaultHandler"> <bean class="org.springframework.web.servlet.mvc.UrlFilenameViewController"/> </property> </bean> <!-- LISTENER'S for SECURITY and JPA--> <bean id="securityFlowExecutionListener" class="org.springframework.webflow.security.SecurityFlowExecutionListener"/> <bean id="jpaFlowExecutionListener" class="org.springframework.webflow.persistence.HibernateFlowExecutionListener"> <constructor-arg ref="entityManagerFactory"/> <constructor-arg ref="transactionManager"/> </bean> <!-- Facelets config --> <bean id="faceletsViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver"> <property name="viewClass" value="org.springframework.faces.mvc.JsfView"/> <property name="prefix" value="/WEB-INF/flows/"/> <property name="suffix" value=".xhtml"/> </bean> This is my full prompt for downloaded: https://rapidshare.com/files/335929555/prompt-jboss.zip thanks A: NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' is defined means that it is unable to locate a bean definition for entityManagerFactory. From your webflow config it is needed by jpaFlowExecutionListener: <bean id="jpaFlowExecutionListener" class="org.springframework.webflow.persistence.HibernateFlowExecutionListener"> <constructor-arg ref="entityManagerFactory"/> <constructor-arg ref="transactionManager"/> </bean> In case this bean is defined in: META-INF/spring/spring-hibernate.xml It should either be imported by a webflow config (WEB-INF/spring/transportes-webflow.xml) <import resource="classpath:META-INF/spring/spring-hibernate.xml" /> Or make sure you have these two files in your Web config listener: <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:META-INF/spring/spring-hibernate.xml /WEB-INF/spring/transportes-webflow.xml ... </param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
{ "language": "en", "url": "https://stackoverflow.com/questions/7571528", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Django Template Arithmetic In my template, I am looping through a list, trying to make a two-column layout. Because of the desired two-column layout, the markup I need to write in the for loop is dependent on whether forloop.counter0 is even or odd. If I had the full power of Python in the template language, determining the parity of forloop.counter0 would be trivial, but unfortunately that is not the case. How can I test whether forloop.counter0 is even or odd using the Django template language, or just as good, is there another way I could get elements in the list to display alternatively in the left and right columns? Thanks in advance! A: You should probably use cycle here instead. As for your question, there is a filter called divisibleby. The philosophy behind Django's template system is to avoid doing any serious logic in the template. Thus they only provide tools to do fairly basic calculations for cases like drawing grids etc. A: You can use the divisibleby filter with forloop.counter: {% if forloop.counter|divisibleby:"2" %}even{% else %}odd{% endif %} A: Use cycle template tag:
{ "language": "en", "url": "https://stackoverflow.com/questions/7571534", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Adding and finding classes that is dynamically added to body - jquery Is there any way to add classes or alter objects that is dynamically added to the body? I am adding a range of objects to the body by javascript. Fot instance Im adding some links that is dynamically generated and added to the body. When they are loaded I need to elect the first of the divs and add a new class to it. I can't seem to find any way to do this... Update the DOM or how should I go around this? There must be a way to alter dynamically added objects. Any clues? Thanks for any help! A: if you added them dynamically, then you can just use the objects you already have. Otherwise you'll need to find them with sizzle. //create the elements var $link1 = $('<a>click me</a>').attr('href','page1.html'); var $link2 = $('<a>click me</a>').attr('href','page2.html'); //append the elements $('#some-links').append($link1).append($link2); //use the element we created $link1.addClass('my-class'); //find the second link element using sizzle $('#some-links>a').eq(1).addClass('my-other-class'); demo: http://jsfiddle.net/PtebM/2/ A: Well of course you caN: var a = $('<a>'); a.html('new link').appendTo('#menu'); a.addClass('border'); or var a = $('<a>'); a.html('new link').appendTo('#menu'); $('#menu a').addClass('border'); fiddle http://jsfiddle.net/4NPqH/ A: Why not just add a class name to your generated elements?. I.e.: $('span').html('Hello world').addClass("fancyText").appendTo('body');
{ "language": "en", "url": "https://stackoverflow.com/questions/7571535", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Authentication in a multi layer architecture I am designing an N-Layer system in .NET that will consist of * *SQL Server 2008 *EF 4 *Repository Layer *Service Layer(Business Logic) On top of this I will have: * *ASP.NET MVC website *external API to be consumed by other clients(built with WCF or ServceStack.NET) I would like to implement the typical username/password auth within the MVC app as well as OpenID/twitter/facebook login options The api will need similar forms of authentication. Where in the architecture is the best place to implement the authentication and are any samples available of how to implement something like this with a .NET Stack? Is a custom Membership provider an option for this? I realize that there are libraries available to implement the openID portion so that is not a concern at the moment but I would like to leave things open to add this in the future. Suggestions? A: Authentication should be done at the user facing point: MVC website and the WCF service. In each point, use the appropriate authentication/authorization mechanism. MVC website: forms authentication (or windows authentication etc.) WCF service: (what method will you be taking, API key, user/name password on every request, secure key, auth cookie etc.) For each point, call the service layer with the credentials used by the requestor (user) and validate it against your database (in the service layer). The service layer should return valid/invalid for the credentials given to it. If it's invalid, have your website or webservice reject any further actions from the user and inform them that it's not valid. If it's valid, have your MVC website create the auth cookie (FormsAuthentication.SetAuthCookie) and your WCF service do the appropriate action for the authentication mechanism you chose. Keep your service layer agnostic of the authentication. It should only respond with whether or not a set of credentials is valid and your front-facing layers should take care of setting the authentication tickets. For Open ID/Twitter/Facebook logins, all the information needed is on the web app (via the login source cookies), so use that to setup your website's auth cookie. A: A basic architecture would be to use the asp.net membership api for your service and web apps calling into the same membership database. Then use an impersonated user to connect to SQL Server. You can then write custom membership providers for the other auth mechanisms or incorporate them all into one membership provider. A: Sorry had to write this as another answer as didn't have enough space in the comments. Configure the membership provider at the IIS level and use the OOTB SQL membership provider to get basic authentication working. You can then write a custom membership the repository layer will be running in the context of the web application either web service or asp.net site so your authentication information will be in the httpcontext, you can then use that to connect through to your database or use an impersonated account i.e. the app pool user to connect instead. You can then write a custom membership provider that authenticates against the other providers if you like and just swap out the standard SQL one for your custom one. A: As an addition to Omar's answer: You could also use a Facade Pattern which handles the authorization and is used by both the WCF and MVC code and provides the API to the business layer. A rule of thumb is: Put authorization at one single point and let the auth-logic be handled by the client(s). Don't spread it over your service layer!
{ "language": "en", "url": "https://stackoverflow.com/questions/7571538", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: move_Image_upload is showing error. I'm using the below code to upload member's profile picture. As I'm new to php, I not able to capture where is the problem. When i try to uplaod a file error shows: "move_uploaded_file() [function.move-uploaded-file]: Unable to move 'C:\Windows\Temp\phpF574.tmp' to '/profilepic/loader.gif'" My code is below: <?php if(isset($_POST['pic'])){ $dir="/profilepic/"; $tmp_nm=$_FILES['profilepic']['tmp_name']; $extension = pathinfo($_FILES['profilepic']['name'], PATHINFO_EXTENSION); if (($extension !=="jpg") && ($extension !=="jpeg") && ($extension !=="png") && ($extension !=="gif")) { exit('<div class="error" align="center">Unknown Image uploaded.</div> '); } $size=filesize($_FILES['profilepic']['tmp_name']); if ($size > 200*1024) { $change='<div class="error">Maximum 200 KB Image Size allowed!</div> '; } $filename=$_FILES['profilepic']['name']; @move_uploaded_file($tmp_nm, $dir.$filename); $arr=array("profilepic='$filename'"); $class_database->update($arr, profile_table, "profileid='".$_SESSION['id']."'"); echo ('<div align="center" class="success">Uploaded your profile picture.</div>'.$php_errormsg); } ?> Also may anyone help me ? A: Unable to move 'C:\Windows\Temp\phpF574.tmp' to '/profilepic/loader.gif'" usually means that you either don't have permission to write to /profilepic or that directory doesn’t exist. * *Make sure /profilepic directory actually exists. *Check $_FILES['profilepic']['error'] for anything other than 0
{ "language": "en", "url": "https://stackoverflow.com/questions/7571544", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Create button in Excel to copy the file? I want to create a button in Excel 2010 that when clicked, it will save the currently opened Excel file and copy it to C:\temp. Is this possible? Perhaps a macro should trigger an exe program, or can be all done within the macro? A: With ActiveWorkbook .Save .SaveCopyAs "C:\Temp\Copy.xls" End With A: In your button's Click event, you can copy the current worksheets into another workbook and then save that in C:\Temp... Something like: Sheets(Array("Sheet1", "Sheet2", "Another Sheet")).Copy ActiveWorkbook.SaveAs "C:\Temp\Copy.xls" ActiveWorkbook.Close
{ "language": "en", "url": "https://stackoverflow.com/questions/7571547", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to load all classes of a jar file at runtime? According to this question, it is possible to load a class from a jar file with: ClassLoader loader = URLClassLoader.newInstance( new URL[] { jarFileURL }, getClass().getClassLoader() ); Class<?> clazz = Class.forName("mypackage.MyClass", true, loader); How to load all classes contained in a jar file? A: The class loader will load a .class file as soon as it's needed. If it's not needed, it won't be loaded. Why do you think that your approach will be an improvement over what the class loader already does? A: You will have to open it as zip file, go through the names, assume all entries ending in .class are class files and load them, ignoring nested classes and such. But....why? A: If you really want to read classes dynamically, leave that to the pros, who already implemented that. Implementing your own classloader is hard. Believe me. I already tried a few times. Use something like OSGi instead, which provides you dynamic class loading and much more.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571551", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Javascript parse float is ignoring the decimals after my comma Here's a simple scenario. I want to show the subtraction of two values show on my site: //Value on my websites HTML is: "75,00" var fullcost = parseFloat($("#fullcost").text()); //Value on my websites HTML is: "0,03" var auctioncost = parseFloat($("#auctioncost").text()); alert(fullcost); //Outputs: 75 alert(auctioncost); //Ouputs: 0 Can anyone tell me what I'm doing wrong? A: Numbers in JS use a . (full stop / period) character to indicate the decimal point not a , (comma). A: It is better to use this syntax to replace all the commas in a case of a million 1,234,567 var string = "1,234,567"; string = string.replace(/[^\d\.\-]/g, ""); var number = parseFloat(string); console.log(number) The g means to remove all commas. Check the Jsfiddle demo here. A: javascript's parseFloat doesn't take a locale parameter. So you will have to replace , with . parseFloat('0,04'.replace(/,/, '.')); // 0.04 A: Why not use globalize? This is only one of the issues that you can run in to when you don't use the english language: Globalize.parseFloat('0,04'); // 0.04 Some links on stackoverflow to look into: * *Jquery Globalization *Globalization in JQuery is not working A: parseFloat parses according to the JavaScript definition of a decimal literal, not your locale's definition. (E.g., parseFloat is not locale-aware.) Decimal literals in JavaScript use . for the decimal point. A: This is "By Design". The parseFloat function will only consider the parts of the string up until in reaches a non +, -, number, exponent or decimal point. Once it sees the comma it stops looking and only considers the "75" portion. * *https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseFloat To fix this convert the commas to decimal points. var fullcost = parseFloat($("#fullcost").text().replace(',', '.')); A: As @JaredPar pointed out in his answer use parseFloat with replace var fullcost = parseFloat($("#fullcost").text().replace(',', '.')); Just replacing the comma with a dot will fix, Unless it's a number over the thousands like 1.000.000,00 this way will give you the wrong digit. So you need to replace the comma remove the dots. // Remove all dot's. Replace the comma. var fullcost = parseFloat($("#fullcost").text().replace(/\./g,'').replace(',', '.')); By using two replaces you'll be able to deal with the data without receiving wrong digits in the output. A: For anyone arriving here wondering how to deal with this problem where commas (,) and full stops (.) might be involved but the exact number format may not be known - this is how I correct a string before using parseFloat() (borrowing ideas from other answers): function preformatFloat(float){ if(!float){ return ''; }; //Index of first comma const posC = float.indexOf(','); if(posC === -1){ //No commas found, treat as float return float; }; //Index of first full stop const posFS = float.indexOf('.'); if(posFS === -1){ //Uses commas and not full stops - swap them (e.g. 1,23 --> 1.23) return float.replace(/\,/g, '.'); }; //Uses both commas and full stops - ensure correct order and remove 1000s separators return ((posC < posFS) ? (float.replace(/\,/g,'')) : (float.replace(/\./g,'').replace(',', '.'))); }; // <-- parseFloat(preformatFloat('5.200,75')) // --> 5200.75 At the very least, this would allow parsing of British/American and European decimal formats (assuming the string contains a valid number). A: What you do wrong is feed parseFloat() with strings that represent decimal fractions in a human-oriented notation, whereas parseFloat() accepts only the standard format corresponding with the JavaScript number literals, which are region-independent, always use the dot as the decimal separator, and have no thousands separator. Futhermore, this parseFloat() function, used in all the answers, is too generous in what it accepts as correct input, preventing the detection of what in most cases is incorrect input: Input Result '1Hello' 1 '1 and 2' 1 '1.2+3.4' 1.2 ' 25 ' 25 In order to get a stricter and therefore better-controlled behavior, I recommend that you implement your own parsing function. Here is mine: // Parse a decimal fraction with specified thousands // and group separators: function /* number */ parse_float ( /* string */ s , // string to parse /* string */ thousep, // thousands separator, empty string if none /* string */ decsep // decimal separator , empty string if none ) { var /* integer */ whole, frac ; // whole and fractinal parts var /* integer */ wnext, fnext; // position of next char after parse var /* integer */ fraclen ; // length of fractional part var /* integer */ ofs ; // offset of the first digit var /* boolean */ done ; // entire string scanned? var /* integer */ sign ; // sign of result var /* number */ res ; // result /* labels */ end: { whole: { // Check parameter types and availability: req_param( 's' , s , 'string' ); req_param( 'thousep', thousep, 'string' ); req_param( 'decsep' , decsep , 'string' ); frac = 0; fraclen = 0; res = NaN; // Account for a possible sign: switch( s.charAt(0) ) { case '-': sign = -1; ofs = 1; break; case '+': sign = +1; ofs = 1; break; default : sign = +1; ofs = 0; break; } [done, wnext, whole] = parse_int_ts( s, ofs, thousep ); if( isNaN( whole ) ) break end; if( done ) break whole; if( s.charAt( wnext ) !== decsep ) break end; [done, fnext, frac] = parse_int( s, 0, wnext + 1 ); if( !done ) break end; fraclen = fnext - wnext - 1; if( fraclen === 0 ) break end; } /* whole: */ res = ( whole + frac / Math.pow( 10, fraclen ) ) * sign; } /* end: */ return res; } // Require that a value be specified and have the expected type: function req_param( /* string */ param, /* variant */ val, /* string */ type ) { var /* string */ errmsg; errmsg = ''; if( val === undefined ) errmsg = 'is undefined'; else if( val === null ) errmsg = 'is null'; else if( typeof val !== type ) errmsg = `must of type \`${type}'`; if( errmsg !== '' ) // there has been an error { throw new Error(`Parameter \`${param}' ${errmsg}.`); } } // Parse an integer with a specified thousands separator: function /* object[] */ parse_int_ts ( /* string */ s , // input string /* integer */ start, // start position /* character */ sep , // thousands separator ) // Returns an array of: // 0: boolean -- entire string was scanned // 1: integer -- index of next character to scan // 2: integer -- resulting inteer { var /* boolean */ full; var /* integer */ next; var /* integer */ res; var /* integer */ len; var /* integer */ psep; var /* integer */ result; res = 0; psep = 0; while( true ) { result = NaN; // mark an error [full, next, res] = parse_int( s, res, start ); len = next - start; if( len === 0 ) break; // nothing parsed if( sep !== '' ) { if( psep > 0 && len !== 3 ) break; // non-first group not 3 digits if( psep === 0 && len > 3 ) break; // first group longer than 3 digits } result = res; // mark success if( s.charAt(next) !== sep ) break; if( full ) break; start = next; psep = next; start = start + 1; } return [full, next, result]; } // Parse a compact of digits beginning at position `start' // in string `s' as an integer number: function /* object[]*/ parse_int ( /* string */ s , // input string /* integer */ init, // initial value /* integer */ start // start position in `s' ) // Returns an array of: // 0: boolean -- entire string was scanned // 1: integer -- index of next character to scan // 2: integer -- result { const /* integer */ ASCII_0 = 48; var /* boolean */ full; // \ var /* integer */ next; // > the return value var /* integer */ res ; // / var /* integer */ n, i; // string length and current position var /* integer */ code; // character code n = s.length; full = true; next = n; res = init; for( i = start; i < n; i += 1 ) { code = s.charCodeAt(i); if( code < ASCII_0 || code >= ASCII_0 + 10 ) { next = i; full = false; break; } res = res * 10 + code - ASCII_0; } if( code === undefined ) res = NaN; return [ full, next, res ]; } And a test program that uses parse_float() to parse numbers of your format: function test( /* string */ s ) { var res; res = parse_float( s, ' ', ',' ); console.log(`${(' ' + `[${s}]`).slice(-12)} => ${res}`); } test( '' ); test( '12' ); test( '12a' ); test( '12,' ); test( '12,345' ); test( '12 345' ); test( '123 45' ); test( '1 234 567' ); test( '12 345 56' ); test( '12345' ); test( '12 435,678' ); test( '+1,2' ); test( '-2 345' ); It writes: [] => NaN [12] => 12 [12a] => NaN [12,] => NaN [12,345] => 12.345 [12 345] => 12345 [123 45] => NaN [1 234 567] => 1234567 [12 345 56] => NaN [12345] => NaN [12 435,678] => 12435.678 [+1,2] => 1.2 [-2 345] => -2345 A: In my case, I already had a period(.) and also a comma(,), so what worked for me was to replace the comma(,) with an empty string like below: parseFloat('3,000.78'.replace(',', '')) This is assuming that the amount from the existing database is 3,000.78. The results are: 3000.78 without the initial comma(,).
{ "language": "en", "url": "https://stackoverflow.com/questions/7571553", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "104" }
Q: div overriding positioning? Is there any way to prevent the main_wrapper from overlapping the footer? the footer has to maintain and position: absolute so that it stays flushed at the bottom of the browser. #page_contain { min-height: 100%; position: relative; } #main_wrapper { width: 950px; height: 800px; margin: 0 auto 25px auto; position: relative; border: 1px solid #000; } #footer { position:absolute; bottom: 0; width: 100%; height: 60px; text-align: center; font-family: Verdana; } html <div id="page_contain"></div> <div id="main_wrapper"></div> <div id="footer"> line 1 <br /> line 2 <br /> line 2 <br /> line 2 <br /> line 2 <br /> line 2 <br /> </div> A: A better way to approach this problem is to apply a fixed positioning to the footer so that it is always at the bottom of the screen. Here's your code in jsfiddle: http://jsfiddle.net/bnryh/ A: Apply the z-index property to your footer: #footer{ [...] z-index: 50; } A: #page_contain { min-height: 100%; position: relative; } #main_wrapper { width: 950px; height: 100%; margin: 0 auto 25px auto; position: relative; border: 1px solid #000; padding-bottom:100px; } #footer { clear:both; position:absolute; bottom: 0; width: 100%; height: 60px; text-align: center; font-family: Verdana; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7571560", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: IE8 ignores ajax response with rails 3.1 I'm using Rails 3.1 and AJAX for creating some models. The view looks like: <%= link_to 'Vote', votes_path, :method => :post, :remote => true %> And the controller: ... def create ... respond_to do |format| format.js { render :layout => false } end end ... Finally, the .js.erb looks like: alert('Hi there!'); In Chrome, FF and Safari it works as I expected, creating the model and displaying the alert. In IE8, it creates the model but it doesn't execute javascript. I think its a weird problem with jquery-rails or something, because with Rails 3.0.9 it works well. Thank you! P.D. I also tried format.js { render :layout => false, :content_type => "text/javascript" } but still doesn't work. A: Does it also happen in other versions of Explorer, newer of older? Have you debugged if the problem is at the time of performing the ajax call or when receiving it? Do you get any error report? Are you including the csrf_meta_tags in the layout? They can really mess up things when performing a POST. http://apidock.com/rails/ActionView/Helpers/CsrfHelper/csrf_meta_tag I would advise you to use the Internet Explorer 8 debugger: http://blogs.msdn.com/b/jscript/archive/2008/03/13/jscript-debugger-in-internet-explorer-8.aspx A: I just found the solution debugging jquery_ujs remote calls. The problem was with charset response (I think). For some reason I must specify explicitly: format.js { render :layout => false, :content_type => "text/javascript; charset=UTF-8" } Please, don't use IE8 :D
{ "language": "en", "url": "https://stackoverflow.com/questions/7571564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Does your average web user understand the concept of the clipboard? I'm designing a web site where I would expect the intended audience to have limited computer skills. An important part of my site's functionality will require the end user to copy an URL that my site generates and use it in emails, or social network postings, or on their own web site. I could write the URL to the clipboard when a button is pushed (like tinyurl.com does). However I'm wondering whether the average user even understands what that means and how to use it. Any guidence will be appreciated. A: There are several paths of though possible, you can make many of the scenarios possible at once. * *Make the URL copied at once. *Make the URL copied when pushing the button. *Make the URL selected at once so the user can copy it directly Of course since the URL is copied at once the two other actions does not need to do anything with the clipboard unless the user has modified the clipboard after the URL was presented. When the URL is copied, at least in the first two steps you could show a message for the user that is has been copied, that makes it useful for those that understand it. For those that might be focused on copying the URL themselves step 3 helps them on their way. Whatever path the user tries should go as smooth as possible without forcing them to understand the benefits offered. In the long run it might help them, but if only used a few times the work of understanding what is going on outweighs the benefit.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571567", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: POSTed values will never be null? I am required for an assignment to check if certain html form fields (type="text") assigned to variables are null. I'm finding that is_null() is not detecting variables to which empty fields are assigned, but empty() does. What is the reason why POSTed values are not null? Also, would isset() be a better choice for this? A: If an input field is not set on your web page, the browser will not send it at all. Therefore you are not seeing null, you are not seeing anything arrive. A: The following should work for you. If there is form element that matches your array key, it will be set to an empty string, if the form element doesn't exist isset will return false. if(!isset($_POST['name'])) A: Because an empty value is semantically more sensible from a data point of view than a null, which is more of a runtime, programming concept. A null value actually cannot be marshalled across the wire in a platform and programming language agnostic fashion.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571568", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: FBGraph and Ruby on Rails Hello and excuse me again I have the next problem: I am using fbgraph on ROR3. I understand that My application need permissions for to know about facebook user. So I need ask for permissions. How could my application (facebook canvas) ask permissions from like button? If need my code please to comment. Thanks in advance A: There are several ways to go about it, one of which is the FB.ui route, using the "oauth" method. You wouldn't necessarily use it directly from a "Like", but rather as the result of a page refresh to a non-fan-gated page or specific user action.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Indexing SQL database i got questions about indexing SQL database: * *Is it better to index boolean column or rather not because there are only 2 options? i know if the table is small then indexing will not change anything, but im asking about table with 1mln records. *If i got two dates ValidFrom and ValidTo is it better to create 1 index with 2 columns or 2 seperate indexes? In 90% of queries i use where validfrom < date && validto > date, but there are also few selects only with validfrom or only with validto *whats the diffrence between clustered and non-clistered index? i cant find any article, so a link would be great A: You both tagged MySQL and SQL-server. This answer is MySQL inspired. * *It depends on many things, but more important than the size is the variation. If about 50% of the values are TRUE, that means the rest of the values (also about 50%) are FALSE and an index will not help much. If only 2% of the values are TRUE and your queries often only need TRUE records, this index will be useful! *If your queries often use both, put both in the index. If one is used more than the other, put that one FIRST in the index, so the composite index can be used for the one field as well. *A clustered index means that the data actually is inside the index. A non-clustered index just points to the data, which is actually stored elsewhere. The PRIMARY KEY in InnoDB is a clustered index. If you want to use Indexes in MySQL, EXPLAIN is your friend! A: This is all for SQL Server, which is what I know about... 1 - Depends on cardinality, but as a rule an index on a single boolean field (BIT in SQL Server) won't be used since it's not very selective. 2 - Make 2 indexes, one with both, and the other with just the second field from the first index. Then you are covered in both cases. 3 - Clustered indexes contain the data for ALL fields at the leaf level (the entire table basically) ordered by your clustered index field. Non-clustered indexes contain only the key fields and any INCLUDEd fields at the leaf level, with a pointer to the clustered index row if you need any other data from other fields for that row. A: * *If you use the "Filtered Index", the number of records up to 2 million with no problems. *Create 1 Non clustered index instead of 2 Filtered Index *Different in user experience, these two aspects are not related to each other nothing. The search index (PK: Primary Key) is different than searching for a range of values ​​(Non clustered Index often used in tracing the value range), in fact finding by PK represented less than 1% queries
{ "language": "en", "url": "https://stackoverflow.com/questions/7571576", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: make dropdown list of person i have a model : public class person { public int id{get;set;} public string name{get;set;} } how can i make a drop down list, from list of person in mvc3 razor by this syntax : @Html.DropDownListFor(...) ? what type must be my persons list? sorry I'm new in mvc3 thanks all A: You should translate that to a List<SelectListItem> if you want to use the build in MVC HtmlHelpers. @Html.DropDownFor(x => x.SelectedPerson, Model.PersonList) Alternatively, you can simply make your own in the template: <select id="select" name="select"> @foreach(var item in Model.PersonList) { <option value="@item.id">@item.name</option> } </select> A: public class PersonModel { public int SelectedPersonId { get; set; } public IEnumerable<Person> persons{ get; set; } } public class Person { public int Id { get; set; } public string Name { get; set; } } then in the controller public ActionResult Index() { var model = new PersonModel{ persons= Enumerable.Range(1,10).Select(x=>new Person{ Id=(x+1), Name="Person"+(x+1) }).ToList() <--- here is the edit }; return View(model);//make a strongly typed view } your view should look like this @model Namespace.Models.PersonModel <div> @Html.DropDownListFor(x=>x.SelectedPersonId,new SelectList(Model.persons,"Id","Name","--Select--")) </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/7571579", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Show Dialog is not showing the dialog box I am trying to find out reason why ShowDialog() is not showing the dialog box for me. I have an application where I have a credential dialog box(A) for the user to enter credentials. And I have another dialog box(B) to display some custom msg based on the user's credential. After the user enter's credentials in A, I am doing something with it. when I am trying to show the msg in B, ShowDialog() is not showing dialog B. Can you guys think of any reason? Here is the code: bool isInternetConnected = class.CheckInternetConnection(ref error); if(!String.IsnUllOrEMpty(error)) { DialogBox dialogBox = new DialogBox(); dialogBox.Title = "Credentials"; dialogBox.State = DialogBox.States.NoFooter; dialogBox.ShowInTaskbar = false; CredentialsContent Credentials = new CredentialsContent(); Credentials.ContentCompleted += new EventHandler<ContentCompletedEventArgs>( dialogBox.OnContentCompleted); dialogBox.MainContent = Credentials; bool? result = dialogBox.ShowDialog(); hasAccess = result.HasValue ? result.Value : false; } UpdateDialog updateDialog = new UpdateDialog(); updateDialog.ShowModal = true; bool? isTrue = updateDialog.ShowDialog(); A: I got it resolved. What was happening is that windows was treating the first window(A) as main window.When it was getting closed the next window(B) as inconsequential. So even with showdialog() it was not showing it. The trick was to define UpdateDialog() at the start of the application. The same question is answered here: Open new window after first
{ "language": "en", "url": "https://stackoverflow.com/questions/7571580", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Distinct join query Possible silly question, but got me stumped. Compare 2 tables and return only distinct columns. SELECT DISTINCT(DM.CLIENT_CODE) FROM DBO.DM_CLIENT DM LEFT JOIN DBO.STG_DM_CLIENT STG ON STG.CLIENT_CODE = DM.CLIENT_CODE Aim of query is to return only new client_codes from DM table (or client_codes not listed in STG table). I tought this would work, however does not. can this query be then used in a case query to validate when new codes exists, then set resultset to 'A' select case when (SELECT DBO.DM_CLIENT.Client_Code FROM DBO.DM_CLIENT DM LEFT JOIN DBO.STG_DM_CLIENT STG ON STG.Client_Code= DM.Client_Code WHERE STG.Client_Code IS NULL GROUP BY DM.Client_Code) then 'A' end from DBO.DM_CLIENT.Client_Code, DBO.STG_DM_CLIENT.Client_Code How can I make that statement to be a conditional statement? A: Sounds like you want to return those from DM that don't exist in STG. SELECT DM.Client_Code FROM DBO.DM_CLIENT As DM LEFT JOIN DBO.STG_DM_CLIENT As STG ON STG.Client_Code= DM.Client_Code WHERE STG.Client_Code IS NULL GROUP BY DM.Client_Code; A: You need to change the query to exclude records where the join failed. SELECT DISTINCT(DM.CLIENT_CODE) FROM DBO.DM_CLIENT AS DM LEFT OUTER JOIN DBO.STG_DM_CLIENT AS STG ON STG.CLIENT_CODE = DM.CLIENT_CODE WHERE STG.CLIENT_CODE IS NULL A: That query is, actually, returning all client_codes. Try this one instead. SELECT DISTINCT(DM.CLIENT_CODE) FROM DBO.DM_CLIENT DM WHERE NOT EXISTS ( SELECT * FROM DBO.STG_DM_CLIENT STG WHERE STG.CLIENT_CODE = DM.CLIENT_CODE ); The query mikerobi proposed is better on efficiency than this one. A: Try either: select distinct dm.client_code from dbo.dm_client dm left join dbo.stg_dm_client stg on stg.client_code = dm.client_code where stg.client_code is null Or: select distinct dm.client_code from dbo.dm_client dm where not exists (select null from stg.client_code stg where dm.client_code = stg.client_code) A: SELECT CLIENT_CODE FROM DBO.DM_CLIENT EXCEPT SELECT CLIENT_CODE FROM DBO.STG_DM_CLIENT; Change EXCEPT to MINUS if you are using Oracle. A: You can do this in different ways: Using NOT IN SELECT * FROM DM_CLIENT WHERE client_code NOT IN ( SELECT client_code FROM STG_DM_CLIENT ) Using EXISTS SELECT * FROM DM_CLIENT dm WHERE NOT EXISTS ( SELECT client_code FROM STG_DM_CLIENT WHERE client_code=dm.client_code ) Using LEFT or RIGHT JOIN SELECT dm.* FROM DM_CLIENT DM LEFT JOIN STG_DM_CLIENT STG ON STG.CLIENT_CODE = DM.CLIENT_CODE WHERE stg.client_code is null In SQL Server 2005 or newer versions you can use OUTER APPLY or EXCEPT
{ "language": "en", "url": "https://stackoverflow.com/questions/7571589", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP image resize function doesn't work properly I want to resize an image PNG with transparence plz help. Here is the code : function createThumb($upfile, $dstfile, $max_width, $max_height){ $size = getimagesize($upfile); $width = $size[0]; $height = $size[1]; $x_ratio = $max_width / $width; $y_ratio = $max_height / $height; if( ($width <= $max_width) && ($height <= $max_height)) { $tn_width = $width; $tn_height = $height; } elseif (($x_ratio * $height) < $max_height) { $tn_height = ceil($x_ratio * $height); $tn_width = $max_width; } else { $tn_width = ceil($y_ratio * $width); $tn_height = $max_height; } if($size['mime'] == "image/jpeg"){ $src = ImageCreateFromJpeg($upfile); $dst = ImageCreateTrueColor($tn_width, $tn_height); imagecopyresampled($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height,$width, $height); imageinterlace( $dst, true); ImageJpeg($dst, $dstfile, 100); } else if ($size['mime'] == "image/png"){ $src = ImageCreateFrompng($upfile); $dst = ImageCreateTrueColor($tn_width, $tn_height); imagecopyresampled($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height,$width, $height); // integer representation of the color black (rgb: 0,0,0) $background = imagecolorallocate($dst, 255, 255, 0); // removing the black from the placeholder imagecolortransparent($dst, $background); // turning off alpha blending (to ensure alpha channel information // is preserved, rather than removed (blending with the rest of the // image in the form of black)) imagealphablending($dst, false); // turning on alpha channel information saving (to ensure the full range // of transparency is preserved) imagesavealpha($dst, true); Imagepng($dst, $dstfile); } else { $src = ImageCreateFromGif($upfile); $dst = ImageCreateTrueColor($tn_width, $tn_height); imagecopyresampled($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height,$width, $height); imagegif($dst, $dstfile); } } The image source : The current result (that I don't want) is : How can I resize the image and maintain the transparency of the background color? Need help, please. Thanks. A: imagecopyresampled is in the wrong place. This should be called after you have set the background colour: $src = ImageCreateFrompng($upfile); $dst = ImageCreateTrueColor($tn_width, $tn_height); // use imagecolorallocatealpha to set BG as transparent: $background = imagecolorallocatealpha($dst, 255, 255, 255, 127); // turning off alpha blending as it's not needed imagealphablending($dst, false); // turning on alpha channel information saving (to ensure the full range // of transparency is preserved) imagesavealpha($dst, true); // Do this here! imagecopyresampled($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height,$width, $height); Imagepng($dst, $dstfile); A: <?php function createthumb($name, $newname, $new_w, $new_h, $border=false, $transparency=true, $base64=false) { if(file_exists($newname)) @unlink($newname); if(!file_exists($name)) return false; $arr = split("\.",$name); $ext = $arr[count($arr)-1]; if($ext=="jpeg" || $ext=="jpg"){ $img = @imagecreatefromjpeg($name); } elseif($ext=="png"){ $img = @imagecreatefrompng($name); } elseif($ext=="gif") { $img = @imagecreatefromgif($name); } if(!$img) return false; $old_x = imageSX($img); $old_y = imageSY($img); if($old_x < $new_w && $old_y < $new_h) { $thumb_w = $old_x; $thumb_h = $old_y; } elseif ($old_x > $old_y) { $thumb_w = $new_w; $thumb_h = floor(($old_y*($new_h/$old_x))); } elseif ($old_x < $old_y) { $thumb_w = floor($old_x*($new_w/$old_y)); $thumb_h = $new_h; } elseif ($old_x == $old_y) { $thumb_w = $new_w; $thumb_h = $new_h; } $thumb_w = ($thumb_w<1) ? 1 : $thumb_w; $thumb_h = ($thumb_h<1) ? 1 : $thumb_h; $new_img = ImageCreateTrueColor($thumb_w, $thumb_h); if($transparency) { if($ext=="png") { imagealphablending($new_img, false); $colorTransparent = imagecolorallocatealpha($new_img, 0, 0, 0, 127); imagefill($new_img, 0, 0, $colorTransparent); imagesavealpha($new_img, true); } elseif($ext=="gif") { $trnprt_indx = imagecolortransparent($img); if ($trnprt_indx >= 0) { //its transparent $trnprt_color = imagecolorsforindex($img, $trnprt_indx); $trnprt_indx = imagecolorallocate($new_img, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']); imagefill($new_img, 0, 0, $trnprt_indx); imagecolortransparent($new_img, $trnprt_indx); } } } else { Imagefill($new_img, 0, 0, imagecolorallocate($new_img, 255, 255, 255)); } imagecopyresampled($new_img, $img, 0,0,0,0, $thumb_w, $thumb_h, $old_x, $old_y); if($border) { $black = imagecolorallocate($new_img, 0, 0, 0); imagerectangle($new_img,0,0, $thumb_w, $thumb_h, $black); } if($base64) { ob_start(); imagepng($new_img); $img = ob_get_contents(); ob_end_clean(); $return = base64_encode($img); } else { if($ext=="jpeg" || $ext=="jpg"){ imagejpeg($new_img, $newname); $return = true; } elseif($ext=="png"){ imagepng($new_img, $newname); $return = true; } elseif($ext=="gif") { imagegif($new_img, $newname); $return = true; } } imagedestroy($new_img); imagedestroy($img); return $return; } //example useage createthumb("1.png", "2.png", 64,64,true, true, false); ?> Hope this can help... I dont deserve credit for this code... just found it op net... enjoy
{ "language": "en", "url": "https://stackoverflow.com/questions/7571604", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Fast user switching with Devise and ActiveAdmin I followed this article to create fast user switching in Devise: http://pivotallabs.com/users/mbarinek/blog/articles/1387-fast-user-switching-with-devise What I don't understand is that in the cucumber file, it says "And I follow the "Sign in as" link for user: "bob"". But there is no sign_in_as_path when I run rake routes. I'm using activeadmin, and when I try to generate the Admin/users view with the addiitional "sign in as" field: column "Sign In As" do |user| link_to "Sign in As", :controller => "signinas", :action => "create" end and this in routes: match "/admin/signinas/create" => "SignInAs#create" It gives me this: ActionController::RoutingError (uninitialized constant SignInAsController::SignInAs): app/controllers/sign_in_as_controller.rb:2:in `<class:SignInAsController>' app/controllers/sign_in_as_controller.rb:1:in `<top (required)>' I don't know how to trigger the create action in the SignInAsController, specified in the article, from admin/users.rb, which contains this: ActiveAdmin.register User do index do column :email column :name column "Sign In As" do |user| link_to "Sign in As", :controller => "signinas", :action => "create" end end end thanks for response
{ "language": "en", "url": "https://stackoverflow.com/questions/7571607", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Problem with jQuery add() issue I have a quick question. My brain is fried and I cannot think :(. Why the following code is not adding tag to MyDivClass: $("div.MyDivClass").add("<a href='' id='test'><span></span></a>"); $("div.MyDivClass a#test").attr("href","www.test.com"); $("div.MyDivClass a#test span").html("text1"); A: The add() method only adds the matched elements to the current jQuery object. It does not add new elements to the DOM. Use append() instead: $("div.MyDivClass").append("<a href='' id='test'><span></span></a>"); A: I think .add only works with a tag like $("div.MyDivClass").add('a'); Try .html instead $("div.MyDivClass").html("<a href='' id='test'><span></span></a>"); A: The add method adds an element to the set of elements contained in a jQuery object. It doesn't actually modify the DOM. For example: var links = $('a'); var linksAndBolds = links.add($('b')); linksAndBolds.css("color", "pink"); To append an element to the DOM tree inside a jQuery onject, call append.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571616", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: document.ready() function slowing my UIs performance I have a UI page in my application which is taking to much time to load. In the HTML source, as you can see, I have a series of .click() jQuery event handlers in the document.ready() function as below: $(document).ready(function() { $("#selectAllCountry").click( function() { $("#" + $(this).attr('rel') + " INPUT[type='checkbox']").attr('checked', true); return false; }); ... and many more... Does it affect my page's performance? Does moving this .click handler in the HTML body will help improve it? One more thing, I am using iframe to load another page in the same domain. But, even if I remove the iframe tag, the performance improvement to is not much. I know, this iframe thing is a major bottleneck in the performance of my application and I will eventually remove it, but there is still something else I need to do for this page. What that particular thing might be? My page is slow slow in performance, even Chrome hung when I tried to get the source in order to reproduce the scenario in jsbin. A: It looks like you could cut down the number of click handlers to 1 as they all seem to do the same thing. If you can put classes of select and deselect on the elements you can just do this: $(".select, .deselect").click( function() { var t = $(this); $("#" + t.attr('rel') + " input:checkbox") .attr('checked', t.hasClass('select')); return false; });
{ "language": "en", "url": "https://stackoverflow.com/questions/7571624", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: How to read an existing html file in the WebBrowser control in WP7? How to read an existing html file in the WebBrowser control in WP7? I have tried: * *Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("abc.htm"); StreamReader reader = new StreamReader(stream); string html = reader.ReadToEnd(); Browser.NavigateToString(html); *Browser.Navigate(new Uri("abc.htm", UriKind.Relative)); *var rs = Application.GetResourceStream(new Uri("abc.htm", UriKind.Relative)); StreamReader sr = new StreamReader(rs.Stream); string html = sr.ReadToEnd(); Browser.NavigateToString(html); All three are not working. The methods 1 and 3 gives NullReferenceException because the stream returns null, basically it is not reading my html file. What is the problem here? How can i fix it? A: When you use number 3, make sure your HTML file has its build type set to 'Content'. A: If you want to use option 2 you must first copy the file to isolated storage if it needs to reference any other files as it's not possible to use relative paths (to other docs, images, js, css, etc.) within a document if loaded directly from the XAP. A: Ok, so here's a sample: in MainPage.xaml: <Grid x:Name="LayoutRoot" Background="Transparent"> <phone:WebBrowser x:Name="MyBrowser" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" /> </Grid> in MainPage.xaml.cs public MainPage() { InitializeComponent(); var rs = Application.GetResourceStream(new Uri("abc.html", UriKind.Relative)); StreamReader sr = new StreamReader(rs.Stream); string html = sr.ReadToEnd(); this.MyBrowser.NavigateToString(html); } make sure you have the file "abc.html" (check for typo, your sample code is "abc.htm") in your project's root folder. Build action as 'Content' and 'copy to output directory' as 'Do not copy'. It should display the page in the browser. A: For the first and third : set the Build Action Property of the html file to "Resource" otherwise it will give you NullReferenceException For the second : browser control in WP7 cannot navigate directly to a html file added in the project. To do this the html file must be located in Isolated Storage. Try that, i hope it'll work. (Mark answer, if its helpful). A: It works fine if you add the command inside a button like: private void htmlLoader(object sender, EventArgs e) { var rs = Application.GetResourceStream(new Uri("abc.html", UriKind.Relative)); StreamReader sr = new StreamReader(rs.Stream); string html = sr.ReadToEnd(); this.MyBrowser.NavigateToString(html); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7571626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Gridview not updating i have a webform with a gridview. i have the UPDATE button next to each row. however when i press the button and edit the field and press UPDATE. it does not change anything. here's the code: <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" CellPadding="4" DataKeyNames="lom_number" DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None" onselectedindexchanged="GridView1_SelectedIndexChanged"> <RowStyle BackColor="#FFFBD6" ForeColor="#333333" /> <Columns> <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" ShowSelectButton="True" /> <asp:BoundField DataField="occurrence_date" HeaderText="occurrence_date" SortExpression="occurrence_date" /> <asp:BoundField DataField="report_date" HeaderText="report_date" SortExpression="report_date" /> <asp:BoundField DataField="report_by" HeaderText="report_by" SortExpression="report_by" /> <asp:BoundField DataField="identified_by" HeaderText="identified_by" SortExpression="identified_by" /> <asp:BoundField DataField="section_c_issue_error_identified_by" HeaderText="section_c_issue_error_identified_by" SortExpression="section_c_issue_error_identified_by" /> <asp:BoundField DataField="section_c_comments" HeaderText="section_c_comments" SortExpression="section_c_comments" /> <asp:BoundField DataField="section_d_investigation" HeaderText="section_d_investigation" SortExpression="section_d_investigation" /> <asp:BoundField DataField="section_e_corrective_action" HeaderText="section_e_corrective_action" SortExpression="section_e_corrective_action" /> <asp:BoundField DataField="section_f_comments" HeaderText="section_f_comments" SortExpression="section_f_comments" /> <asp:BoundField DataField="pre_practice_code" HeaderText="pre_practice_code" SortExpression="pre_practice_code" /> <asp:BoundField DataField="pre_contact" HeaderText="pre_contact" SortExpression="pre_contact" /> <asp:BoundField DataField="lom_number" HeaderText="lom_number" InsertVisible="False" ReadOnly="True" SortExpression="lom_number" /> <asp:BoundField DataField="windows_user" HeaderText="windows_user" SortExpression="windows_user" /> <asp:BoundField DataField="computer_name" HeaderText="computer_name" SortExpression="computer_name" /> <asp:BoundField DataField="time_stamp" HeaderText="time_stamp" SortExpression="time_stamp" /> </Columns> <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" /> <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" /> <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" /> <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" /> <AlternatingRowStyle BackColor="White" /> </asp:GridView> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:LOM %>" SelectCommand="SELECT * FROM [Main_LOM_Form]" ConflictDetection="CompareAllValues" DeleteCommand="DELETE FROM [Main_LOM_Form] WHERE [lom_number] = @original_lom_number AND (([occurrence_date] = @original_occurrence_date) OR ([occurrence_date] IS NULL AND @original_occurrence_date IS NULL)) AND (([report_date] = @original_report_date) OR ([report_date] IS NULL AND @original_report_date IS NULL)) AND (([report_by] = @original_report_by) OR ([report_by] IS NULL AND @original_report_by IS NULL)) AND (([identified_by] = @original_identified_by) OR ([identified_by] IS NULL AND @original_identified_by IS NULL)) AND (([section_c_issue_error_identified_by] = @original_section_c_issue_error_identified_by) OR ([section_c_issue_error_identified_by] IS NULL AND @original_section_c_issue_error_identified_by IS NULL)) AND (([section_c_comments] = @original_section_c_comments) OR ([section_c_comments] IS NULL AND @original_section_c_comments IS NULL)) AND (([section_d_investigation] = @original_section_d_investigation) OR ([section_d_investigation] IS NULL AND @original_section_d_investigation IS NULL)) AND (([section_e_corrective_action] = @original_section_e_corrective_action) OR ([section_e_corrective_action] IS NULL AND @original_section_e_corrective_action IS NULL)) AND (([section_f_comments] = @original_section_f_comments) OR ([section_f_comments] IS NULL AND @original_section_f_comments IS NULL)) AND (([pre_practice_code] = @original_pre_practice_code) OR ([pre_practice_code] IS NULL AND @original_pre_practice_code IS NULL)) AND (([pre_contact] = @original_pre_contact) OR ([pre_contact] IS NULL AND @original_pre_contact IS NULL)) AND [windows_user] = @original_windows_user AND [computer_name] = @original_computer_name AND [time_stamp] = @original_time_stamp" InsertCommand="INSERT INTO [Main_LOM_Form] ([occurrence_date], [report_date], [report_by], [identified_by], [section_c_issue_error_identified_by], [section_c_comments], [section_d_investigation], [section_e_corrective_action], [section_f_comments], [pre_practice_code], [pre_contact], [windows_user], [computer_name], [time_stamp]) VALUES (@occurrence_date, @report_date, @report_by, @identified_by, @section_c_issue_error_identified_by, @section_c_comments, @section_d_investigation, @section_e_corrective_action, @section_f_comments, @pre_practice_code, @pre_contact, @windows_user, @computer_name, @time_stamp)" OldValuesParameterFormatString="original_{0}" UpdateCommand="UPDATE [Main_LOM_Form] SET [occurrence_date] = @occurrence_date, [report_date] = @report_date, [report_by] = @report_by, [identified_by] = @identified_by, [section_c_issue_error_identified_by] = @section_c_issue_error_identified_by, [section_c_comments] = @section_c_comments, [section_d_investigation] = @section_d_investigation, [section_e_corrective_action] = @section_e_corrective_action, [section_f_comments] = @section_f_comments, [pre_practice_code] = @pre_practice_code, [pre_contact] = @pre_contact, [windows_user] = @windows_user, [computer_name] = @computer_name, [time_stamp] = @time_stamp WHERE [lom_number] = @original_lom_number AND (([occurrence_date] = @original_occurrence_date) OR ([occurrence_date] IS NULL AND @original_occurrence_date IS NULL)) AND (([report_date] = @original_report_date) OR ([report_date] IS NULL AND @original_report_date IS NULL)) AND (([report_by] = @original_report_by) OR ([report_by] IS NULL AND @original_report_by IS NULL)) AND (([identified_by] = @original_identified_by) OR ([identified_by] IS NULL AND @original_identified_by IS NULL)) AND (([section_c_issue_error_identified_by] = @original_section_c_issue_error_identified_by) OR ([section_c_issue_error_identified_by] IS NULL AND @original_section_c_issue_error_identified_by IS NULL)) AND (([section_c_comments] = @original_section_c_comments) OR ([section_c_comments] IS NULL AND @original_section_c_comments IS NULL)) AND (([section_d_investigation] = @original_section_d_investigation) OR ([section_d_investigation] IS NULL AND @original_section_d_investigation IS NULL)) AND (([section_e_corrective_action] = @original_section_e_corrective_action) OR ([section_e_corrective_action] IS NULL AND @original_section_e_corrective_action IS NULL)) AND (([section_f_comments] = @original_section_f_comments) OR ([section_f_comments] IS NULL AND @original_section_f_comments IS NULL)) AND (([pre_practice_code] = @original_pre_practice_code) OR ([pre_practice_code] IS NULL AND @original_pre_practice_code IS NULL)) AND (([pre_contact] = @original_pre_contact) OR ([pre_contact] IS NULL AND @original_pre_contact IS NULL)) AND [windows_user] = @original_windows_user AND [computer_name] = @original_computer_name AND [time_stamp] = @original_time_stamp"> <DeleteParameters> <asp:Parameter Name="original_lom_number" Type="Int32" /> <asp:Parameter DbType="Date" Name="original_occurrence_date" /> <asp:Parameter DbType="Date" Name="original_report_date" /> <asp:Parameter Name="original_report_by" Type="String" /> <asp:Parameter Name="original_identified_by" Type="String" /> <asp:Parameter Name="original_section_c_issue_error_identified_by" Type="String" /> <asp:Parameter Name="original_section_c_comments" Type="String" /> <asp:Parameter Name="original_section_d_investigation" Type="String" /> <asp:Parameter Name="original_section_e_corrective_action" Type="String" /> <asp:Parameter Name="original_section_f_comments" Type="String" /> <asp:Parameter Name="original_pre_practice_code" Type="String" /> <asp:Parameter Name="original_pre_contact" Type="String" /> <asp:Parameter Name="original_windows_user" Type="String" /> <asp:Parameter Name="original_computer_name" Type="String" /> <asp:Parameter Name="original_time_stamp" Type="DateTime" /> </DeleteParameters> <UpdateParameters> <asp:Parameter DbType="Date" Name="occurrence_date" /> <asp:Parameter DbType="Date" Name="report_date" /> <asp:Parameter Name="report_by" Type="String" /> <asp:Parameter Name="identified_by" Type="String" /> <asp:Parameter Name="section_c_issue_error_identified_by" Type="String" /> <asp:Parameter Name="section_c_comments" Type="String" /> <asp:Parameter Name="section_d_investigation" Type="String" /> <asp:Parameter Name="section_e_corrective_action" Type="String" /> <asp:Parameter Name="section_f_comments" Type="String" /> <asp:Parameter Name="pre_practice_code" Type="String" /> <asp:Parameter Name="pre_contact" Type="String" /> <asp:Parameter Name="windows_user" Type="String" /> <asp:Parameter Name="computer_name" Type="String" /> <asp:Parameter Name="time_stamp" Type="DateTime" /> <asp:Parameter Name="original_lom_number" Type="Int32" /> <asp:Parameter DbType="Date" Name="original_occurrence_date" /> <asp:Parameter DbType="Date" Name="original_report_date" /> <asp:Parameter Name="original_report_by" Type="String" /> <asp:Parameter Name="original_identified_by" Type="String" /> <asp:Parameter Name="original_section_c_issue_error_identified_by" Type="String" /> <asp:Parameter Name="original_section_c_comments" Type="String" /> <asp:Parameter Name="original_section_d_investigation" Type="String" /> <asp:Parameter Name="original_section_e_corrective_action" Type="String" /> <asp:Parameter Name="original_section_f_comments" Type="String" /> <asp:Parameter Name="original_pre_practice_code" Type="String" /> <asp:Parameter Name="original_pre_contact" Type="String" /> <asp:Parameter Name="original_windows_user" Type="String" /> <asp:Parameter Name="original_computer_name" Type="String" /> <asp:Parameter Name="original_time_stamp" Type="DateTime" /> </UpdateParameters> <InsertParameters> <asp:Parameter DbType="Date" Name="occurrence_date" /> <asp:Parameter DbType="Date" Name="report_date" /> <asp:Parameter Name="report_by" Type="String" /> <asp:Parameter Name="identified_by" Type="String" /> <asp:Parameter Name="section_c_issue_error_identified_by" Type="String" /> <asp:Parameter Name="section_c_comments" Type="String" /> <asp:Parameter Name="section_d_investigation" Type="String" /> <asp:Parameter Name="section_e_corrective_action" Type="String" /> <asp:Parameter Name="section_f_comments" Type="String" /> <asp:Parameter Name="pre_practice_code" Type="String" /> <asp:Parameter Name="pre_contact" Type="String" /> <asp:Parameter Name="windows_user" Type="String" /> <asp:Parameter Name="computer_name" Type="String" /> <asp:Parameter Name="time_stamp" Type="DateTime" /> </InsertParameters> </asp:SqlDataSource> here is the query that it i intercepted with james' help: updateQuery "UPDATE [Main_LOM_Form] SET [occurrence_date] = @occurrence_date, [report_date] = @report_date, [report_by] = @report_by, [identified_by] = @identified_by, [section_c_issue_error_identified_by] = @section_c_issue_error_identified_by, [section_c_comments] = @section_c_comments, [section_d_investigation] = @section_d_investigation, [section_e_corrective_action] = @section_e_corrective_action, [section_f_comments] = @section_f_comments, [pre_practice_code] = @pre_practice_code, [pre_contact] = @pre_contact, [windows_user] = @windows_user, [computer_name] = @computer_name, [time_stamp] = @time_stamp WHERE [lom_number] = @original_lom_number AND (([occurrence_date] = @original_occurrence_date) OR ([occurrence_date] IS NULL AND @original_occurrence_date IS NULL)) AND (([report_date] = @original_report_date) OR ([report_date] IS NULL AND @original_report_date IS NULL)) AND (([report_by] = @original_report_by) OR ([report_by] IS NULL AND @original_report_by IS NULL)) AND (([identified_by] = @original_identified_by) OR ([identified_by] IS NULL AND @original_identified_by IS NULL)) AND (([section_c_issue_error_identified_by] = @original_section_c_issue_error_identified_by) OR ([section_c_issue_error_identified_by] IS NULL AND @original_section_c_issue_error_identified_by IS NULL)) AND (([section_c_comments] = @original_section_c_comments) OR ([section_c_comments] IS NULL AND @original_section_c_comments IS NULL)) AND (([section_d_investigation] = @original_section_d_investigation) OR ([section_d_investigation] IS NULL AND @original_section_d_investigation IS NULL)) AND (([section_e_corrective_action] = @original_section_e_corrective_action) OR ([section_e_corrective_action] IS NULL AND @original_section_e_corrective_action IS NULL)) AND (([section_f_comments] = @original_section_f_comments) OR ([section_f_comments] IS NULL AND @original_section_f_comments IS NULL)) AND (([pre_practice_code] = @original_pre_practice_code) OR ([pre_practice_code] IS NULL AND @original_pre_practice_code IS NULL)) AND (([pre_contact] = @original_pre_contact) OR ([pre_contact] IS NULL AND @original_pre_contact IS NULL)) AND [windows_user] = @original_windows_user AND [computer_name] = @original_computer_name AND [time_stamp] = @original_time_stamp" string what am i doing wrong? A: I would suggest adding an OnUpdating event handler so you can look at the CommandText before the query is executed. That should help you identify if there's an issue with the query. In the markup: <asp:SqlDataSource ID="SqlDataSource1" runat="server" OnUpdating="SqlDataSource1_Updating" ... > In the code-behind: protected void SqlDataSource1_Updating(object sender, SqlDataSourceCommandEventArgs e) { string updateQuery = e.Command.CommandText; //inspect the update query }
{ "language": "en", "url": "https://stackoverflow.com/questions/7571630", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Swipe to delete moves the UITableViewCell to the left I use custom code to create cells that get displayed on a UITableView. When a row is swiped, the delete button appears on the far right of the cell as expected. However it causes the contents of the cell to move to the left (partly off screen). This kind of behaviour didn't happen when using the cells that are built in to the framework. A: The UIView property autoresizingMask allows you to specify how your subviews should behave when their superview (in this case the UITableViewCell's contentView) gets resized. See the View Programming Guide for iOS for more information. A: Isn't it because your content is bound to the right edge? A: Although this answer may be too late, I believe the problem is due to the fact that you happen to be adding your content directly to the cell by writing something like: MyView* myView = [[MyView alloc] init]; [cell addSubview : myView]; This happens to be good; however, your content will be affected by any change that takes place within the cell. If, on the other hand, you want your views to remain intact while anything else happens to the cell, you must add your content as subviews of the cell's contentView: MyView* myView = [[MyView alloc] init]; [[cell contentView] addSubview : myView]; I do hope this helps. Cheers!
{ "language": "en", "url": "https://stackoverflow.com/questions/7571633", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to put a toolbar directly beneath a tabpanel Here is my current code (with heights/widths omitted): myapp.cards.addvehicle = new Ext.TabPanel({ scroll: 'vertical', id: "home2", layout:{ type:"vbox", }, dockedItems: [{ xtype: 'toolbar', dock: 'top' }] }); but it places the toolbar above the tabpanel. Adding a toolbar in the items part of the configuration object doesn't produce the desired result either. Has anyone been able to accomplish this and if so, how? Note: I believe that by default in extjs4 the toolbar appear below the tabbar when docked at the top, although I can't confirm this. Many thanks. A: the bottom on the docked toolbar item: myapp.cards.addvehicle = new Ext.TabPanel({ scroll: 'vertical', id: "home2", layout:{ type:"vbox", }, dockedItems: [{ xtype: 'toolbar', dock: '**bottom**' }] });
{ "language": "en", "url": "https://stackoverflow.com/questions/7571634", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Fastest way to check if a value exists in a list What is the fastest way to check if a value exists in a very large list? A: It sounds like your application might gain advantage from the use of a Bloom Filter data structure. In short, a bloom filter look-up can tell you very quickly if a value is DEFINITELY NOT present in a set. Otherwise, you can do a slower look-up to get the index of a value that POSSIBLY MIGHT BE in the list. So if your application tends to get the "not found" result much more often then the "found" result, you might see a speed up by adding a Bloom Filter. For details, Wikipedia provides a good overview of how Bloom Filters work, and a web search for "python bloom filter library" will provide at least a couple useful implementations. A: You could put your items into a set. Set lookups are very efficient. Try: s = set(a) if 7 in s: # do stuff edit In a comment you say that you'd like to get the index of the element. Unfortunately, sets have no notion of element position. An alternative is to pre-sort your list and then use binary search every time you need to find an element. A: The original question was: What is the fastest way to know if a value exists in a list (a list with millions of values in it) and what its index is? Thus there are two things to find: * *is an item in the list, and *what is the index (if in the list). Towards this, I modified @xslittlegrass code to compute indexes in all cases, and added an additional method. Results Methods are: * *in--basically if x in b: return b.index(x) *try--try/catch on b.index(x) (skips having to check if x in b) *set--basically if x in set(b): return b.index(x) *bisect--sort b with its index, binary search for x in sorted(b). Note mod from @xslittlegrass who returns the index in the sorted b, rather than the original b) *reverse--form a reverse lookup dictionary d for b; then d[x] provides the index of x. Results show that method 5 is the fastest. Interestingly the try and the set methods are equivalent in time. Test Code import random import bisect import matplotlib.pyplot as plt import math import timeit import itertools def wrapper(func, *args, **kwargs): " Use to produced 0 argument function for call it" # Reference https://www.pythoncentral.io/time-a-python-function/ def wrapped(): return func(*args, **kwargs) return wrapped def method_in(a,b,c): for i,x in enumerate(a): if x in b: c[i] = b.index(x) else: c[i] = -1 return c def method_try(a,b,c): for i, x in enumerate(a): try: c[i] = b.index(x) except ValueError: c[i] = -1 def method_set_in(a,b,c): s = set(b) for i,x in enumerate(a): if x in s: c[i] = b.index(x) else: c[i] = -1 return c def method_bisect(a,b,c): " Finds indexes using bisection " # Create a sorted b with its index bsorted = sorted([(x, i) for i, x in enumerate(b)], key = lambda t: t[0]) for i,x in enumerate(a): index = bisect.bisect_left(bsorted,(x, )) c[i] = -1 if index < len(a): if x == bsorted[index][0]: c[i] = bsorted[index][1] # index in the b array return c def method_reverse_lookup(a, b, c): reverse_lookup = {x:i for i, x in enumerate(b)} for i, x in enumerate(a): c[i] = reverse_lookup.get(x, -1) return c def profile(): Nls = [x for x in range(1000,20000,1000)] number_iterations = 10 methods = [method_in, method_try, method_set_in, method_bisect, method_reverse_lookup] time_methods = [[] for _ in range(len(methods))] for N in Nls: a = [x for x in range(0,N)] random.shuffle(a) b = [x for x in range(0,N)] random.shuffle(b) c = [0 for x in range(0,N)] for i, func in enumerate(methods): wrapped = wrapper(func, a, b, c) time_methods[i].append(math.log(timeit.timeit(wrapped, number=number_iterations))) markers = itertools.cycle(('o', '+', '.', '>', '2')) colors = itertools.cycle(('r', 'b', 'g', 'y', 'c')) labels = itertools.cycle(('in', 'try', 'set', 'bisect', 'reverse')) for i in range(len(time_methods)): plt.plot(Nls,time_methods[i],marker = next(markers),color=next(colors),linestyle='-',label=next(labels)) plt.xlabel('list size', fontsize=18) plt.ylabel('log(time)', fontsize=18) plt.legend(loc = 'upper left') plt.show() profile() A: As stated by others, in can be very slow for large lists. Here are some comparisons of the performances for in, set and bisect. Note the time (in second) is in log scale. Code for testing: import random import bisect import matplotlib.pyplot as plt import math import time def method_in(a, b, c): start_time = time.time() for i, x in enumerate(a): if x in b: c[i] = 1 return time.time() - start_time def method_set_in(a, b, c): start_time = time.time() s = set(b) for i, x in enumerate(a): if x in s: c[i] = 1 return time.time() - start_time def method_bisect(a, b, c): start_time = time.time() b.sort() for i, x in enumerate(a): index = bisect.bisect_left(b, x) if index < len(a): if x == b[index]: c[i] = 1 return time.time() - start_time def profile(): time_method_in = [] time_method_set_in = [] time_method_bisect = [] # adjust range down if runtime is too long or up if there are too many zero entries in any of the time_method lists Nls = [x for x in range(10000, 30000, 1000)] for N in Nls: a = [x for x in range(0, N)] random.shuffle(a) b = [x for x in range(0, N)] random.shuffle(b) c = [0 for x in range(0, N)] time_method_in.append(method_in(a, b, c)) time_method_set_in.append(method_set_in(a, b, c)) time_method_bisect.append(method_bisect(a, b, c)) plt.plot(Nls, time_method_in, marker='o', color='r', linestyle='-', label='in') plt.plot(Nls, time_method_set_in, marker='o', color='b', linestyle='-', label='set') plt.plot(Nls, time_method_bisect, marker='o', color='g', linestyle='-', label='bisect') plt.xlabel('list size', fontsize=18) plt.ylabel('log(time)', fontsize=18) plt.legend(loc='upper left') plt.yscale('log') plt.show() profile() A: def check_availability(element, collection: iter): return element in collection Usage check_availability('a', [1,2,3,4,'a','b','c']) I believe this is the fastest way to know if a chosen value is in an array. A: 7 in a Clearest and fastest way to do it. You can also consider using a set, but constructing that set from your list may take more time than faster membership testing will save. The only way to be certain is to benchmark well. (this also depends on what operations you require) A: a = [4,2,3,1,5,6] index = dict((y,x) for x,y in enumerate(a)) try: a_index = index[7] except KeyError: print "Not found" else: print "found" This will only be a good idea if a doesn't change and thus we can do the dict() part once and then use it repeatedly. If a does change, please provide more detail on what you are doing. A: Be aware that the in operator tests not only equality (==) but also identity (is), the in logic for lists is roughly equivalent to the following (it's actually written in C and not Python though, at least in CPython): for element in s: if element is target: # fast check for identity implies equality return True if element == target: # slower check for actual equality return True return False In most circumstances this detail is irrelevant, but in some circumstances it might leave a Python novice surprised, for example, numpy.NAN has the unusual property of being not being equal to itself: >>> import numpy >>> numpy.NAN == numpy.NAN False >>> numpy.NAN is numpy.NAN True >>> numpy.NAN in [numpy.NAN] True To distinguish between these unusual cases you could use any() like: >>> lst = [numpy.NAN, 1 , 2] >>> any(element == numpy.NAN for element in lst) False >>> any(element is numpy.NAN for element in lst) True Note the in logic for lists with any() would be: any(element is target or element == target for element in lst) However, I should emphasize that this is an edge case, and for the vast majority of cases the in operator is highly optimised and exactly what you want of course (either with a list or with a set). A: If you only want to check the existence of one element in a list, 7 in list_data is the fastest solution. Note though that 7 in set_data is a near-free operation, independently of the size of the set! Creating a set from a large list is 300 to 400 times slower than in, so if you need to check for many elements, creating a set first is faster. Plot created with perfplot: import perfplot import numpy as np def setup(n): data = np.arange(n) np.random.shuffle(data) return data, set(data) def list_in(data): return 7 in data[0] def create_set_from_list(data): return set(data[0]) def set_in(data): return 7 in data[1] b = perfplot.bench( setup=setup, kernels=[list_in, set_in, create_set_from_list], n_range=[2 ** k for k in range(24)], xlabel="len(data)", equality_check=None, ) b.save("out.png") b.show() A: This is not the code, but the algorithm for very fast searching. If your list and the value you are looking for are all numbers, this is pretty straightforward. If strings: look at the bottom: * *-Let "n" be the length of your list *-Optional step: if you need the index of the element: add a second column to the list with current index of elements (0 to n-1) - see later *Order your list or a copy of it (.sort()) *Loop through: * *Compare your number to the n/2th element of the list * *If larger, loop again between indexes n/2-n *If smaller, loop again between indexes 0-n/2 *If the same: you found it *Keep narrowing the list until you have found it or only have 2 numbers (below and above the one you are looking for) *This will find any element in at most 19 steps for a list of 1.000.000 (log(2)n to be precise) If you also need the original position of your number, look for it in the second, index column. If your list is not made of numbers, the method still works and will be fastest, but you may need to define a function which can compare/order strings. Of course, this needs the investment of the sorted() method, but if you keep reusing the same list for checking, it may be worth it. A: Edge case for spatial data There are probably faster algorithms for handling spatial data (e.g. refactoring to use a k-d tree), but the special case of checking if a vector is in an array is useful: * *If you have spatial data (i.e. cartesian coordinates) *If you have integer masks (i.e. array filtering) In this case, I was interested in knowing if an (undirected) edge defined by two points was in a collection of (undirected) edges, such that (pair in unique_pairs) | (pair[::-1] in unique_pairs) for pair in pairs where pair constitutes two vectors of arbitrary length (i.e. shape (2,N)). If the distance between these vectors is meaningful, then the test can be expressed by a floating point inequality like test_result = Norm(v1 - v2) < Tol and "Value exists in List" is simply any(test_result). Example code and dummy test set generators for integer pairs and R3 vector pairs are below. # 3rd party import numpy as np import numpy.linalg as LA import matplotlib.pyplot as plt # optional try: from tqdm import tqdm except ModuleNotFoundError: def tqdm(X, *args, **kwargs): return X print('tqdm not found. tqdm is a handy progress bar module.') def get_float_r3_pairs(size): """ generate dummy vector pairs in R3 (i.e. case of spatial data) """ coordinates = np.random.random(size=(size, 3)) pairs = [] for b in coordinates: for a in coordinates: pairs.append((a,b)) pairs = np.asarray(pairs) return pairs def get_int_pairs(size): """ generate dummy integer pairs (i.e. case of array masking) """ coordinates = np.random.randint(0, size, size) pairs = [] for b in coordinates: for a in coordinates: pairs.append((a,b)) pairs = np.asarray(pairs) return pairs def float_tol_pair_in_pairs(pair:np.ndarray, pairs:np.ndarray) -> np.ndarray: """ True if abs(a0 - b0) <= tol & abs(a1 - b1) <= tol for (ai1, aj2), (bi1, bj2) in [(a01, a02), ... (aik, ajl)] NB this is expected to be called in iteration so no sanitization is performed. Parameters ---------- pair : np.ndarray pair of vectors with shape (2, M) pairs : np.ndarray collection of vector pairs with shape (N, 2, M) Returns ------- np.ndarray (pair in pairs) | (pair[::-1] in pairs). """ m1 = np.sum( abs(LA.norm(pairs - pair, axis=2)) <= (1e-03, 1e-03), axis=1 ) == 2 m2 = np.sum( abs(LA.norm(pairs - pair[::-1], axis=2)) <= (1e-03, 1e-03), axis=1 ) == 2 return m1 | m2 def get_unique_pairs(pairs:np.ndarray) -> np.ndarray: """ apply float_tol_pair_in_pairs for pair in pairs Parameters ---------- pairs : np.ndarray collection of vector pairs with shape (N, 2, M) Returns ------- np.ndarray pair if not ((pair in rv) | (pair[::-1] in rv)) for pair in pairs """ pairs = np.asarray(pairs).reshape((len(pairs), 2, -1)) rv = [pairs[0]] for pair in tqdm(pairs[1:], desc='finding unique pairs...'): if not any(float_tol_pair_in_pairs(pair, rv)): rv.append(pair) return np.array(rv)
{ "language": "en", "url": "https://stackoverflow.com/questions/7571635", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1198" }
Q: Using COPY FROM in postgres - absolute filename of local file I'm trying to import a csv file using the COPY FROM command with postgres. The db is stored on a linux server, and my data is stored locally, i.e. C:\test.csv I keep getting the error: ERROR: could not open file "C:\test.csv" for reading: No such file or directory SQL state: 58P01 I know that I need to use the absolute path for the filename that the server can see, but everything I try brings up the same error Can anyone help please? Thanks A: Quote from the PostgreSQL manual: The file must be accessible to the server and the name must be specified from the viewpoint of the server So you need to copy the file to the server before you can use COPY FROM. If you don't have access to the server, you can use psql's \copy command which is very similar to COPY FROM but works with local files. See the manual for details.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571636", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Writing Escape Characters to a Csv File in Python I'm using the csv module in python and escape characters keep messing up my csv's. For example, if I had the following: import csv rowWriter = csv.writer(open('bike.csv', 'w'), delimiter = ",") text1 = "I like to \n ride my bike" text2 = "pumpkin sauce" rowWriter.writerow([text1, text2]) rowWriter.writerow(['chicken','wings']) I would like my csv to look like: I like to \n ride my bike,pumpkin sauce chicken,wings But instead it turns out as I like to ride my bike,pumpkin sauce chicken,wings I've tried combinations of quoting, doublequote, escapechar and other parameters of the csv module, but I can't seem to make it work. Does anyone know whats up with this? *Note - I'm also using codecs encode("utf-8"), so text1 really looks like "I like to \n ride my bike".encode("utf-8") A: The problem is not with writing them to the file. The problem is that \n is a line break when inside '' or "". What you really want is either 'I like to \\n ride my bike' or r'I like to \n ride my bike' (notice the r prefix). A: Firstly, it is not obvious why you want r"\n" (two bytes) to appear in your file instead of "\n" (one byte). What is the consumer of the output file meant to do? Use ast.evaluate_literal() on each input field? If your actual data contains any of (non-ASCII characters, apostrophes, quotes), then I'd be very wary of serialising it using repr(). Secondly, you have misreported either your code or your output (or both). The code that you show actually produces: "I like to ride my bike",pumpkin sauce chicken,wings Thirdly, about your "I like to \n ride my bike".encode("utf-8"): str_object.encode("utf-8") is absolutely pointless if str_object contains only ASCII bytes -- it does nothing. Otherwise it raises an exception. Fourthly, this comment: I don't need to call encode anymore, now that I'm using the raw string. There are a lot of unicode characters in the text that I am using, so before I started using the raw string I was using encode so that csv could read the unicode text doesn't make any sense -- as I've said, "ascii string".encode('utf8') is pointless. Consider taking a step ot two backwards, and explain what you are really trying to do: where does your data come from, what's in it, and most importantly, what does the process that is going to read the file going to do?
{ "language": "en", "url": "https://stackoverflow.com/questions/7571642", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: qtranslate plugin and ajax requests I'm trying to obtain the correct content for each language (I'm using qtranslate plugin in Wordpress environment) loaded by Ajax calls. Every time, contents are shown up only in the default language. I'm thinking about to pass the default-language-qtranslate variable into the ajax calls but I don't know how. Maybe someone out here has already solved this issue..? Thanks guys A: This will help you to fix the default language request in Mailpress, or any other plugin. Search in code for link request "ajax.php". Replace "ajax.php" with ajax.php/?lang='.qtrans_getLanguage()
{ "language": "en", "url": "https://stackoverflow.com/questions/7571643", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Implementing my own OnTouchListener I would like to create my own OnTouchListener. Then I would like to encapsulate it to a .jar file for making it reusable. This is my specific OnTouchListener: public class TouchableView extends View implements OnTouchListener{ myTouch t=null; public TouchableView(Context context) { super(context); // Set KeyListener to ourself this.setOnTouchListener(this); } public TouchableView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // Set KeyListener to ourself this.setOnTouchListener(this); } public TouchableView(Context context, AttributeSet attrs) { super(context, attrs); // Set KeyListener to ourself this.setOnTouchListener(this); } public void setmyTouch(myTouch listener) { t = listener; } @Override public boolean onTouch(View v, MotionEvent event) { if(event.getAction()==MotionEvent.ACTION_DOWN){ t.downTouch(); return true; } return false; } public interface myTouch{ public abstract boolean downTouch(); } } This is how I'm trying to use it: public class MyTouchImplement extends Activity implements myTouch{ /** Called when the activity is first created. */ TextView tv; int i=0; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); tv=(TextView) findViewById(R.id.tv); TouchableView view = (TouchableView) findViewById(R.id.view); view.setmyTouch(this); } @Override public boolean downTouch() { i++; tv.setText(i+""); return true; } } I would like to make it work for every component that the OnTouchListener works with. A: The following works for me. Please check and see if this helps. Please feel free to modify the constructor to suit your needs. For this test I used a linear layout with two TextView (txtX, txtY) fields and one GridLayout control. MineSweeperOnTouch.java public class MineSweeperOnTouch implements View.OnTouchListener { private View gridLayout = null; private TextView txtX = null; private TextView txtY = null; public MineSweeperOnTouch(View aGridLayout, TextView aTxtX, TextView aTxtY) { this.gridLayout = aGridLayout; this.txtX = aTxtX; this.txtY = aTxtY; } public boolean onTouch(View v, MotionEvent event) { txtTimeX.setText("X: " + String.valueOf(event.getX())); txtY.setText("Y: " + String.valueOf(event.getY())); return true; } } MainActivity.java (code snippet only) ------------------------------------- public class MainActivity extends Activity { private MineSweeperOnTouch gridLayoutListener = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //custom code starts here final View gridLayout = findViewById(R.id.gridLayout); final TextView txtX = (TextView) findViewById(R.id.txtX); final TextView txtY = (TextView) findViewById(R.id.txtY); gridLayoutListener = new MineSweeperOnTouch(gridLayout, txtX, txtY); gridLayout.setOnTouchListener(gridLayoutListener); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } } A: You've created an awfully complicated web of dependencies that you should simplify. For example you shouldn't be passing around the activity object like that. Also you when creating an Activity class you do not need to redefine the constructors. Using the super constructors is fine. What you do need to define are the onCreate onStart onPause onStop onDestroy methods. I highly suggest you read the Activity Documentation A simpler implementation than what you have above, would be to get rid of your myTouch interface. Remove the implements OnTouchListener from the TouchableView class and create a OnTouchListener class inside your activity class. It would look something like this: public class MyTouchActivity extends Activity{ TouchableView tv; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); tv = new TouchableView(); tv.setOnTouchListener(new MyOwnTouchListener()); } class MyOnTouchListener implements OnTouchListener{ public boolean onTouchEvent(View v, MotionEvent e){ switch(e.getAction){ case (MotionEvent.TOUCH_DOWN) MyTouchActivity.this.touchDown(); break; } } } public boolean touchDown(){ //touch down happened } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7571644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: In CSS, is there any way to keep the hover properties for links after overriding the normal state? I have default properties defined for my links like this: a{ color: blue; } a:hover{ color: red; } The problem is that I lose the all the hover properties when I do something like this: #header a{ color: gray; } So to keep the hover working as I defined it before in the defaults, I'd have to declare it again: #header a:hover{ color: red; } Is there any way to do this without loosing the original hover action defined? A: Unfortunately, if you want it to work in all browsers, you'll have to override it. a { color:blue; } a:hover { color:red; } #header a { color:grey; } #header a:hover { color:red; } Example. Alternatively, you can make use of !important. Usually this is a sign that something weird is going on in your css, but this seems to be the only alternative to duplicating your css. a { color:blue; } a:hover { color:red !important; } #header a:hover { color:red; } Example. You could also make use of a css compiler such as sass or less which would let you write it in a manor where you aren't duplicating effort - but that's beyond the scope of this question. A: You're over-riding the styles with a cascade. Putting "#header a" gives that style more weight than the original style. You can over-ride it with a !important (although I wouldn't recommend it). Here's an article that explains this concept. A: One way you can do this is to specify the default style as !important. Using !important is usually a sure fire sign that your code can be improved however in this context, and without re-defining the styles, it seems like the best choice (best I know of right now). a:hover{ color:blue !important; } Working Example Also note that if you do go down the route of using the specific selector that you can combine both selectors together to reduce code duplication. a:hover, #header a:hover{ color: red;}
{ "language": "en", "url": "https://stackoverflow.com/questions/7571650", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can you render a single instance of an object through a partial using collections? So for example, if I have a partial that works with @users as a collection, i.e. <%= render :partial => 'dashboard/dashboard_pane', :collection => @users %> where @users = User.all But DOESNT seem to work with a single instance <%= render :partial => 'dashboard/dashboard_pane', :collection => @user %> where @user = User.first The questions is, why? A: I guess it's looping an Array. Try with: [ User.first ] A: I think the answer is because it's not a collection :) As @apneadiving said try putting it in an array. A very contrived alternative is to make it into a bona fide collection: @users = User.find_all_by_id(@user.id) I wouldn't recommend this though. A: To use this partial with a single object, you should't be calling it with :collection. Try this instead: <%= render :partial => 'dashboard/dashboard_pane', :object => @users.first %>
{ "language": "en", "url": "https://stackoverflow.com/questions/7571651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Resize/Crop image from specific area I am trying to find a PHP image library script that allow me to select specific area (x, y) from large image and then crop/resize to smaller image. It must not distort the image (resize by stretching and skewing the pics). It may need to 'Zoom In' (or something?) if necessary to overcome this problem. Which PHP image library script can do this? A: WideImage And here is crop demo. E.g. WideImage::load('a.png')->crop(50, 50, 30, 20)->saveToFile('b.jpg'); A: Either GD (http://php.net/manual/en/book.image.php) or ImageMagick (http://php.net/manual/en/book.imagick.php) can do cropping operations. On the frontend, Jcrop (http://code.google.com/p/jcrop/) is a nice jQuery plugin if you're looking to do this via a page. A: You can use GD to achieve that. Im guessing something like this could do it: /** *@param string $pathToImage The original image (jpg) *@param string $outputImage The name of the output image (jpg) *@param int $x The top x coordinate of the portion you want to grab *@param int $y The top y coordinate of the portion you want to grab *@param int $width the width of the portion you want to grab *@param int $height the height of the portion you want to grab *@return void */ function getImagePortion($pathToImage, $outputImage, $x, $y, $width, $height) { $im = imagecreatefromjpeg($pathToImage); $portion = imagecreatetruecolor($width, $height); imagecopyresampled($portion, $im, 0, 0, $x, $y, $width, $height, imagesx($im), imagesy($im)); imagejpeg($portion, $outputImage, 100); } A: I happened to LOVE this class http://www.verot.net/php_class_upload.htm I know it says upload, but you can also handle local files, and if they are images, it gives you a ton of pretty cool features. you can look them up in http://www.verot.net/php_class_upload_samples.htm GL
{ "language": "en", "url": "https://stackoverflow.com/questions/7571652", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: About animation in android widget I want move widget (such as button) with animation described in XML. But after animation done, that widget return first position. How can I stop widget where I want position. A: The animation only describes the movement of the widget, and when the animation finishes the widget is redrawn at its original location. You need to move the widget to the final location immediately before you animate it. Then when the animation is finished the widget new position will be the same as its position at the end of the animation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571653", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Inheritance and method scope in Java In the following example pseudocode: public class MyPanel extends JPanel { public void reset() { this.clear(); clear(); } public void clear() { System.out.println("FAIL"); } }; public class MySpecialPanel extends MyPanel { public void clear() { System.out.println("Hello, world"); } }; When calling (new MySpecialPanel()).reset() shouldn't both this.clear() and clear() resolve in the same scope? Is there any difference between this.clear() and clear()? A: public void reset() { this.clear(); clear(); } In the code above, that calls the same method twice. There is no difference between clear() and this.clear(). You can explicitly call the superclasses method with super.clear(). A: There is no difference between this.clear() and clear(). You have a MySpecialPanel object and the clear() method on that object is called twice. To call the superclass's clear, you must use super.clear() So, you do something like this -- public void reset() { clear(); super.clear(); } A: in your code: public void reset() { this.clear(); clear(); } both this.clear() and clear() are the same. this is a keyword for setting the scope of the call inside the class itself super sets the scope to the class itself and the superclass A: Stating the obvious as many have already responded - when you call clear() on an object, that object is in scope; when you use this you are referring to that same object in context.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571654", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: run one scheduler at a time I have two beans which is running the scheduler <bean id="eventService" class="xxx.xxxx.xxxxx.EventSchedulerImpl"> </bean> <bean id="UpdateService" class="xxx.xxxx.xxxxx.UpdateSchedulerImpl"> </bean> I want to make sure only one scheduler is running at time when EventSchedulerImpl is running UpdateSchedulerImpl should not run also implemented "StatefulJob" on both the scheduler will that work? do i need to do more? appericate your idea guys A: One way would be to configure a special task executor so that it contains only one thread in its thread pool, and configure its queue capacity so that jobs can be kept "on-hold". So only one task can run at a time with this task executor, and the other task will get queued. But I don't like this approach. Having a single-threaded task executor seems like a recipe for problems down the road. What I would do is simply write a wrapper service that calls your target services in the order you need. Then schedule the wrapper service instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571658", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: taking a screenshot of some element in the html So I was wondering, if I have a div which contains a maps of google maps rendered with some makers and I want to take a picture of that element how can I do this?.I found this solutions it's a approach of what I need but the problem it's that sending a url doesn't help me, I need the specific Div with all the markers. For the server side i'm using C# and for the cliente, asp.net with jquery. Also the google maps apiV3 to handle the maps A: Take a look at the Canvas2Image library by Nihilogic Labs: http://www.nihilogic.dk/labs/canvas2image/ Here's an example of how to take a screenshot of an element through JavaScript: var oCanvas = document.getElementById("thecanvas"); Canvas2Image.saveAsPNG(oCanvas); EDIT You might also take a look at Html2Canvas and FlashCanvas too. I believe one of them has support for earlier browsers (those which don't support HTML5). A: Use the method in the link you mentioned and crop the resulting image to the dimensions of your div. You can use myDiv.getBoundingClientRect() in JavaScript to get the dimensions of your div. Using the WebBrowser control, you can manipulate the document using html or JavaScript to get the page in the state you need to take your screenshot. A: Have you considered using the Google Maps Static API - this will render a map image, with markers on it, as a PNG.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571659", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Automatic non-RESTful routes in Rails 3? We have an app with a large number of non-RESTful, verb-oriented controllers. I remember that long ago, before Rails got the REST religion, you could get automatic routes and helpers for those. Is there any way to still do this? It's a pain to keep adding GETs every time we add an action, and our app (or perhaps our collective development brain) just doesn't lend itself to RESTfulness. A: You can still use a default route like this: match ':controller(/:action(/:id))' to match paths like * */monkey/play */monkey/see/1 */monkey/hear/1 */monkey/eat/1 A: You can use the "magic route", I believe it's still in the routes file by default, but if you don't have it here it is: # This is a legacy wild controller route that's not recommended for RESTful applications. # Note: This route will make all actions in every controller accessible via GET requests. # match ':controller(/:action(/:id(.:format)))'
{ "language": "en", "url": "https://stackoverflow.com/questions/7571661", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: MVC file locations and function locations. PHP Zend I just got a job where i would be working with MVC and they knew i didn't know it but would help me learn. I am fairly confident with my PHP or i was until now and had some questions about MVC but figured i would catch on quickly but this is looking like its more in depth than i expected. And i have a few questions.. * *Is their an easier way to tell which PHP file is a certain class without having to view its contents? Using netbeans. *I understand the inheritance of the class that it is extends but some functions access different classes out of the directory they are in and are different from the global included Zend library. Is their a way to find these classes easier? *All modules have their own MVC framework with their API and core files for them. Some module files will extend(for example) the Application/Library/Engine/Engine.php. They create and instance and then call a unknown method getApi($param,$param) to the example.php and the class. I cannot find the getApi function in any core class, local classes, or zend. Am i looking in the incorrect places? Can i have a more straightforward view on what the class inherits? Im pretty lost here but i will keep trying until i figure it out. Thanks A: * *In Zend the Files are names after the class. So Zend_Database_Adpater() is placed in Zend/Database/Adapter.php. *I hope answer 1. helps here too. Zend has a search path where it looks for objects. *mh... Sounds like you need a Zend Tutorial and a documentation for the start. Normaly you don't need to crawl into the core. I guess i am not a big help here, sorry about that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571670", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Grails domain ID column validation issue I have a simple domain object class MyDomain { String id String name static constraints = { id unique:true name nullable:true } static mapping = { table 'schema.MyDomain' id column:'MY_ID', type:'string', generator:'assigned' } } The issue I am having is when I call validate on the object, it returns true even when the id field is null. I had thought that all columns were nullable:false unless explicitly stated otherwise. If I change the line id unique:true to id unique:true, nullable:false then it seems to work fine. My main question is, why do I have to explicitly set nullable for the ID column? It is just a small line of code, but I don't like just adding in the tag of code without understanding why in case it is a symptom of a bigger problem. A: The id column is auto generated and auto populated(when versioning is turned on[true by default]) and you shouldn't have to declare a new one. This default id column is nullable:false by default and you can still set the mapping properties and id generation strategies like you have done above against it. However if you want to define the default constraints for all domain in you app, you can do it globally by setting thwe following in your config.groovy file. grails.gorm.default.constraints = { myShared(nullable:true, size:1..20) } For more on constraints see the Grails documentation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571673", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I return a list of records and true or false if a joined record exists using SQL? I have three tables. Table A: TableA_ID, Description Table B: TableB_ID, TableA_ID, TableC_ID Table C: TableC_ID, Various Other columns Table B may contain zero or more records linking a record from Table C to a record in table A I want a query that will return ALL records from Table A and an additional column that will be True or False dependent on whether any related records exist in Table B for a specific TableC_ID value. Any help mucho appreciated. Cheers Stewart A: SELECT a.TableA_ID, a.Description, CASE WHEN b.tableC_ID IS NOT NULL THEN 'True' ELSE 'False' END AS DoesExist FROM TableA a LEFT JOIN TableB b ON a.TableA_ID = b.TableA_ID AND b.TableC_ID = 123 -- Add your specific value here
{ "language": "en", "url": "https://stackoverflow.com/questions/7571680", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using a constructor on a JavaScript static instance I'm writing a JavaScript library in which I want some methods and properties public and other private. The following seems a great way of doing this whilst wrapping everything up into a single object. (function (window) { var Thing = function() { // private var var variable = "value"; return { // public method method:function() { alert(variable); } } }(); window.Thing = Thing; })(window); Thing.method(); Which is great. (Mostly grabbed from here). However, I'd still like to be able to use the constructor of Thing to pass in some arguments. Is there anyway I can provide a constructor in the return statement, or use prototype to override the constructor? So I can call: Thing(stuff); Right now, if I try that it causes: Uncaught TypeError: Property 'Thing' of object [object DOMWindow] is not a function Which makes sense as it's not returning itself, but ideally it'd be possible to call a constructor. OR, is this just baaaad and I should steer clear of some or all of this? A: To accomplish what you are asking, do something like this: (function (window) { var thingMaker= function(stuff) { // private var var variable = "value"; return { // public method method:function() { alert(variable); } alertStuff:function() { alert(stuff); } } }; window.thingMaker= thingMaker; })(window); var myThing = window.thingMaker(stuff); myThing.alertStuff() More information can be found by searching the googlenets for Douglas Crockford. Some great and very informative videos by him are available on yui theater. But I would have to ask, why create another framework when there are already so many great ones out there (jquery,prototype,yui,dojo to name a few) A: Thing is already created, so you are always going to be too late to call a 'constructor'. You could pass variables in like this: (function (window, var1, var2) { var Thing = function() { // private var var variable = "value"; return { // public method method:function() { alert(variable); } } }(); window.Thing = Thing; })(window, var1, var2); A: Thing is an Object with one method called method: { // public method method:function() { alert(variable); } } Thing.method(); // alerts "value" You could return instead: function () { alert(arguments) } Then Thing(6,5,4); // alerts 6,5,4
{ "language": "en", "url": "https://stackoverflow.com/questions/7571682", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Vim Pre-Exit (Esc Key) Command? Right now in Vim when I go to a new line (or press 'p' or 'o' in normal mode) I get a lovely automatic indent, that also disappears if I exit insert mode without adding anything to it. Is there a way to bind something to before I exit insert mode, such as inserting a phantom character then removing it? A: Argh, I just read about this exact thing like two days ago but I can't remember where. Anyway, the trick is to input a character right after <CR> and delete it immediately. There are a bunch of ways to do it: <CR>a<Esc>x <CR>a<C-w> <CR>a<BS> --EDIT-- Vim being Vim there are probably many other ways. To automate these, you need to add a mapping to your .vimrc: inoremap <CR> <CR>a<BS> " insert mode mapping for <CR> nnoremap o oa<BS> " normal mode mapping for o But I'm not sure you should overwrite defaults like that. --EDIT-- However, what is annoying with Vim's default behaviour is that you may need to do some <Tab><Tab><Tab><Tab> before actually inputing some text on non-indented line or do == when you are done or rely on the automatic indentation rules for your language at the next <CR>. All that can be skipped by using <S-S> which puts you in INSERT mode right at the correct indentation level. A: Try either cc or S in normal mode to change a line with respect to indention. No need for phantom characters. :h cc :h S A: A mapping like the following should do the trick: imap <esc> <esc>:s/\s\+$//<CR> This one deletes trailing characters when you press esc in insert mode.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571688", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Can I somehow save circular data structures with JSON or something similar? When trying to save some data about the game world in a file using JSON, I get that good ol' JSON circular reference error. Is there a way to save circular data types? Also, I'm running this with node.js, not inside a browser. Basically, over time, the player gets some units. These units are saved to a list inside the player object, but are given the player himself as an argument, so they know who's their owner. Something like this: Player = function() { this.power = 0 this.units = [new Unit(this)]; } Unit = function(owner) { owner.power++; } A: @Bane, in answer to how to include the cycle.js Put it in your lib folder for your project and include it via a script tag if you're doing it on the client side. On the server side you could include the code in the file that you need the circular reference in; that's simple but really the wrong way to work. Better bet is to build it out as a module, check this tutorial on howtonode.org for the specifics. Your overall best bet though is to refactor so that you don't need the circular reference.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571691", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Multiple values IN Normally IN is used with one value: SELECT * FROM data WHERE f1 IN (<subquery>) It is possible to use it with multiple values: SELECT * FROM data WHERE f1 IN (<subquery>) OR f2 IN (<subquery>); But can I remove duplication, something like: SELECT * FROM data WHERE ANY(f1, f1) IN (<subquery>) I tried to use CTE, but it also require subquery. A: Assuming you have columns col1,col2, and col3 and that you're looking for col1 and col2 in your subquery (for the sake of illustration), you can do something like: select col1,col2,col3 from table where (col1,col2) in (<subquery>) group by 1,2,3; As long as <subquery> is of the (rough) form select col1,col2 from <blah>, then you'll end up with distinct (col1,col2,col3) triples where (col1,col2) pairs appear in <subquery>. A: I might write this in terms of set operators: SELECT * FROM data WHERE EXISTS ( VALUES(f1, f2) INTERSECT SELECT(<subquery>) ) A: While both solutions works, I have found that fastest (unfortunately not shortest) way is to use CTE: WITH x AS (<subquery>) SELECT * FROM data WHERE f1 IN (SELECT * FROM x) OR f2 (SELECT * FROM x)
{ "language": "en", "url": "https://stackoverflow.com/questions/7571693", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: JSTL : Find the total of size of two lists I have two lists on a page and showing combined size of these two lists. Here is my code <c:set var="totalAvailableVehicles" value="${fn:length(searchResult.availableVehicleList)}"/> <c:set var="totalUvailableVehicles" value="${fn:length(searchResult.unavailableVehicleList)}"/> <c:out value="${totalAvailableVehicles + totalUvailableVehicles}"/></strong> record found matching your search criteria</p> Is there any better way to achieve same without writing custom tag/functions? A: I'm not sure what you mean with a "better way". This looks perfectly fine. You could also do it without <c:set>: <strong><c:out value="${fn:length(searchResult.availableVehicleList) + fn:length(searchResult.unavailableVehicleList)}"/></strong> record found matching your search criteria</p> However, whether that's better readable/maintainable is questionable. You could also move that to a getter method of the SearchResult bean: public int getTotalResultSize() { return availableVehicleList.size() + unavailableVehicleList.size(); } with <strong>${searchResult.totalResultSize}</strong> record found matching your search criteria</p> Note that the <c:out> is not necessary here (it'll work as good in JSP 2.0 and newer). The benefit of <c:out> is the HTML-escaping of user-controlled input in order to prevent XSS attacks, but since it concerns here non-user-controlled input of type int, there is really no XSS attack risk. After all, it really doesn't matter as long as you end up with a degree of readability/maintainability which your team agrees in.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571702", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Entity Framework - Load entities with child entity What I am trying is to load all the A entities in the database together with B entities. The relationship between them is Every A entitiy has one B entitiy. The project I am working on has a repository pattern and it has an All() method as below. public class EFRepository<T> : IRepository<T> where T : class, IObjectWithChangeTracker { private IObjectSet<T> objectset; private IObjectSet<T> ObjectSet { get { if (objectset == null) { objectset = UnitOfWork.Context.GetObjectSet<T>(); } return objectset; } } public virtual IQueryable<T> All() { return ObjectSet.AsQueryable(); } } Is there any way that I can force B entities to eager load. What I've found is there there is no Include method on the IQueryable that returns from the All() method. I am happy to add a new member to repositroy so it can allow the client to use eager loading. But how can I do it? A: The problem is that IQueryable is agnostic of what's backing it, and Include is an Entity Framework feature. You could have an IQueryable that uses LINQ to Objects instead, and Include wouldn't make sense there. The easiest thing would be to change the type of All() to an IObjectSet, from which you should have access to an Include extension method. If you can't change the return type of All, you will have to structure your queries in such a way that they pull in the child elements eagerly. IList<Parent> parentsWithEagerLoadedChildren = parentRepo.All() .Select(p => new {p, p.Children}).ToList() // EF will attach the children to each parent .Select(p => p.p).ToList(); // Now that everything is loaded, select just the parents A: You can create your own extension method which will allow you to use Include(path) against any IQueryable<T>: public static IQueryable<TSource> Include<TSource> (this IQueryable<TSource> source, string path) { var objectQuery = source as ObjectQuery<TSource>; if (objectQuery != null) { return objectQuery.Include(path); } return source; } There's a full explanation on Julie Lerman's blog: http://thedatafarm.com/blog/data-access/agile-entity-framework-4-repository-part-5-iobjectset/
{ "language": "en", "url": "https://stackoverflow.com/questions/7571703", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Multiple Security Token Services in Windows Identity Framework I have an asp.net mvc 3 web app that needs to support SSO from multiple STSs based on the subdomain the user requests. So requests for https://weylandyutani.mydomain.com should trust the Weyland-Yutani STS and https://tyrell.mycomain.com should trust the Tyrell STS. Most WIF resources talk about enabling STSes in the application's web config. Is there an accepted way to do this dynamically without reinventing the wheel? A: In scenarios like this, you would typically use an intermediate STS (referred to an "RP-STS" or "Federation Provider" that will handle all trust relationships for you. That is: your app trusts the RP-STS, then the RP-STS would trust Weyland-Yutani, Tyrell, etc. Adding an RP-STS simplifies things quite a bit, especially if each of the identity STSs send you claims that are all different from what you require in your app. For example: Tyrell might send you "name", "lastname" and "e-mail". Weyland might send "Username", "e-mail". The RP-STS would normalize the claims set to whatever your app needs. The way you hint the RP-STS where to redirect the user is through the whr parameter (which stands for "Home Realm"). Your app would look at the request URL and then append the whr parameter before redirecting to the RP-STS. All the above is extensively documented in the "Federation with Multiple Partners" chapter of this book. If you don't want to build/acquire and deploy your own RP-STS (depending on the deployment model of your app, you could use ADFS v2.0 for example), you could use Access Control Service from Windows Azure. This other chapter explains how it would work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571704", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }