text
stringlengths
8
267k
meta
dict
Q: CSS Selector "(A or B) and C"? This should be simple, but I'm having trouble finding the search terms for it. Let's say I have this: <div class="a c">Foo</div> <div class="b c">Bar</div> In CSS, how can I create a selector that matches something that matches "(.a or .b) and .c"? I know I could do this: .a.c,.b.c { /* CSS stuff */ } But, assuming I'm going to have to do this sort of logic a lot, with a variety of logical combinations, is there a better syntax? A: No. Standard CSS does not provide the kind of thing you're looking for. However, you might want to look into LESS and SASS. These are two projects which aim to extend default CSS syntax by introducing additional features, including variables, nested rules, and other enhancements. They allow you to write much more structured CSS code, and either of them will almost certainly solve your particular use case. Of course, none of the browsers support their extended syntax (especially since the two projects each have different syntax and features), but what they do is provide a "compiler" which converts your LESS or SASS code into standard CSS, which you can then deploy on your site. A: Not yet, but there is the experimental :is() (formerly :matches()) pseudo-class selector that does just that: :is(.a .b) .c { /* style properties go here */ } You can find more info on it here and here. Currently, most browsers support its initial version :any(), which works the same way, but will be replaced by :is(). We just have to wait a little more before using this everywhere (I surely will). A: For those reading this >= 2021: I found success using the :is() selector: *:is(.a, .b).c{...} A: is there a better syntax? No. CSS' or operator (,) does not permit groupings. It's essentially the lowest-precedence logical operator in selectors, so you must use .a.c,.b.c. A: If you have this: <div class="a x">Foo</div> <div class="b x">Bar</div> <div class="c x">Baz</div> And you only want to select the elements which have .x and (.a or .b), you could write: .x:not(.c) { ... } but that's convenient only when you have three "sub-classes" and you want to select two of them. Selecting only one sub-class (for instance .a): .a.x Selecting two sub-classes (for instance .a and .b): .x:not(.c) Selecting all three sub-classes: .x
{ "language": "en", "url": "https://stackoverflow.com/questions/7517429", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "239" }
Q: How to enable TLS/SSL in java, Spring / CXF for Web Service? I have a simple WebService defined in Spring config: <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cxf="http://cxf.apache.org/core" xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:wsa="http://cxf.apache.org/ws/addressing" xmlns:http="http://cxf.apache.org/transports/http/configuration" xmlns:wsrm-policy="http://schemas.xmlsoap.org/ws/2005/02/rm/policy" xmlns:wsrm-mgr="http://cxf.apache.org/ws/rm/manager" xmlns:httpj="http://cxf.apache.org/transports/http-jetty/configuration" xsi:schemaLocation=" http://cxf.apache.org/transports/http/configuration http://cxf.apache.org/schemas/configuration/http-conf.xsd http://schemas.xmlsoap.org/ws/2005/02/rm/policy http://schemas.xmlsoap.org/ws/2005/02/rm/wsrm-policy.xsd http://cxf.apache.org/ws/rm/manager http://cxf.apache.org/schemas/configuration/wsrm-manager.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd http://cxf.apache.org/transports/http-jetty/configuration http://cxf.apache.org/schemas/configuration/http-jetty.xsd"> <import resource="classpath:META-INF/cxf/cxf.xml" /> <import resource="classpath:META-INF/cxf/cxf-extension-*.xml" /> <bean id="logInbound" class="org.apache.cxf.interceptor.LoggingInInterceptor"/> <bean id="logOutbound" class="org.apache.cxf.interceptor.LoggingOutInterceptor"/> <bean id="cxf" class="org.apache.cxf.bus.CXFBusImpl"> <property name="inInterceptors"> <list> <ref bean="logInbound"/> </list> </property> <property name="outInterceptors"> <list> <ref bean="logOutbound"/> </list> </property> <property name="outFaultInterceptors"> <list> <ref bean="logOutbound"/> </list> </property> <property name="inFaultInterceptors"> <list> <ref bean="logInbound"/> </list> </property> </bean> <httpj:engine-factory bus="cxf"> <httpj:engine port="9001"> <httpj:threadingParameters minThreads="10" maxThreads="100" /> <httpj:connector> <bean class="org.eclipse.jetty.server.bio.SocketConnector"> <property name="port" value="9001" /> </bean> </httpj:connector> <httpj:handlers> <bean class="org.eclipse.jetty.server.handler.DefaultHandler" /> </httpj:handlers> <httpj:sessionSupport>true</httpj:sessionSupport> </httpj:engine> </httpj:engine-factory> <bean id="serviceFactory" class="org.apache.cxf.jaxws.support.JaxWsServiceFactoryBean" scope="prototype"> <property name="serviceConfigurations"> <list> <bean class="org.apache.cxf.jaxws.support.JaxWsServiceConfiguration" /> <bean class="org.apache.cxf.aegis.databinding.XFireCompatibilityServiceConfiguration" /> <bean class="org.apache.cxf.service.factory.DefaultServiceConfiguration" /> </list> </property> </bean> <bean id="eventWebService" class="org.myapp.EventWS"> <property name="timeout" value="${timeoutWS}" /> </bean> <jaxws:endpoint id="event" implementor="#eventWebService" address="${event.endpoint}"> <jaxws:serviceFactory> <ref bean="serviceFactory" /> </jaxws:serviceFactory> </jaxws:endpoint> It works like a simple WS at event.endpoint=http://localhost:9001/event But now, I want to secure that connection with TLS using server private key. I know how to do this using SSLContext ( http://download.oracle.com/javase/6/docs/api/javax/net/ssl/SSLContext.html ), but Spring is something new to me. I guess I need to create a new Endpoint with another configuration? Or use another ServiceFactory? A: You must configure the engine factory with an SSL enabled connector. Maybe this helps: http://docs.codehaus.org/display/JETTY/How+to+configure+SSL A: I've managed to create a new engine with SSL <httpj:engine port="9101"> <httpj:tlsServerParameters> <sec:clientAuthentication want="true" required="true" /> </httpj:tlsServerParameters> <httpj:threadingParameters minThreads="10" maxThreads="100" /> <httpj:connector> <bean class="org.eclipse.jetty.server.ssl.SslSocketConnector"> <property name="port" value="9101" /> <property name="keystore" value= "./config/keystore-gateway" /> <property name="password" value= "pass" /> <property name="keyPassword" value= "pass" /> </bean> </httpj:connector> <httpj:handlers> <bean class="org.eclipse.jetty.server.handler.DefaultHandler" /> </httpj:handlers> <httpj:sessionSupport>true</httpj:sessionSupport> </httpj:engine> It works in browser with SSL. How to enable mutual authentication now ? A: <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:sec="http://cxf.apache.org/configuration/security" xmlns:http="http://cxf.apache.org/transports/http/configuration" xmlns:httpj="http://cxf.apache.org/transports/http-jetty/configuration" xmlns:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation=" http://cxf.apache.org/configuration/security http://cxf.apache.org/schemas/configuration/security.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd http://cxf.apache.org/transports/http-jetty/configuration http://cxf.apache.org/schemas/configuration/http-jetty.xsd http://cxf.apache.org/transports/http/configuration http://cxf.apache.org/schemas/configuration/http-conf.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd"> <context:property-placeholder location="classpath:override.properties" ignore-resource-not-found="true" properties-ref="defaultProperties"/> <util:properties id="defaultProperties"> <prop key="keyManager.keystore">certs/localhost.jks</prop> </util:properties> <http:destination name="yourDestination" /> <httpj:engine-factory> <httpj:engine port="yourPort"> <httpj:tlsServerParameters> <sec:keyManagers keyPassword="password"> <sec:keyStore type="JKS" password="password" file="${keys.keystore}"/> </sec:keyManagers> <sec:trustManagers> <sec:keyStore type="JKS" password="password" file="certs/keystore.jks"/> </sec:trustManagers> <sec:cipherSuitesFilter> <!-- these filters ensure that a ciphersuite with export-suitable or null encryption is used, but exclude anonymous Diffie-Hellman key change as this is vulnerable to man-in-the-middle attacks --> <sec:include>.*_EXPORT_.*</sec:include> <sec:include>.*_EXPORT1024_.*</sec:include> <sec:include>.*_WITH_DES_.*</sec:include> <sec:include>.*_WITH_DES40_.*</sec:include> <sec:include>.*_WITH_AES_.*</sec:include> <sec:exclude>.*_DH_anon_.*</sec:exclude> </sec:cipherSuitesFilter> <!-- ### HIL <sec:clientAuthentication want="true" required="true"/> ### HIL ENDE --> </httpj:tlsServerParameters> </httpj:engine> </httpj:engine-factory> You need to have a keystore file such as shown on line 17. You also should have a properites file with the necessary credentials to validate against the keystore. (For a introduction into keystore and keystore authentication see here: http://en.wikipedia.org/wiki/Keystore)
{ "language": "en", "url": "https://stackoverflow.com/questions/7517434", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I simplify token prediction DFA? Lexer DFA results in "code too large" error I'm trying to parse Java Server Pages using ANTLR 3. Java has a limit of 64k for the byte code of a single method, and I keep running into a "code too large" error when compiling the Java source generated by ANTLR. In some cases, I've been able to fix it by compromising my lexer. For example, JSP uses the XML "Name" token, which can include a wide variety of characters. I decided to accept only ASCII characters in my "Name" token, which drastically simplified some tests in the and lexer allowed it to compile. However, I've gotten to the point where I can't cut any more corners, but the DFA is still too complex. What should I do about it? Are there common mistakes that result in complex DFAs? Is there a way to inhibit generation of the DFA, perhaps relying on semantic predicates or fixed lookahead to help with the prediction? Writing this lexer by hand will be easy, but before I give up on ANTLR, I want to make sure I'm not overlooking something obvious. Background ANTLR 3 lexers use a DFA to decide how to tokenize input. In the generated DFA, there is a method called specialStateTransition(). This method contains a switch statement with a case for each state in the DFA. Within each case, there is a series of if statements, one for each transition from the state. The condition of each if statement tests an input character to see if it matches the transition. These character-testing conditions can be very complex. They normally have the following form: int ch = … ; /* "ch" is the next character in the input stream. */ switch(s) { /* "s" is the current state. */ … case 13 : if ((('a' <= ch) && (ch <= 'z')) || (('A' <= ch) && (ch <= 'Z')) || … ) s = 24; /* If the character matches, move to the next state. */ else if … A seemingly minor change to my lexer can result in dozens of comparisons for a single transition, several transitions for each state, and scores of states. I think that some of the states being considered are impossible to reach due to my semantic predicates, but it seems like semantic predicates are ignored by the DFA. (I could be misreading things though—this code is definitely not what I'd be able to write by hand!) I found an ANTLR 2 grammar in the Jsp2x tool, but I'm not satisfied with its parse tree, and I want to refresh my ANTLR skills, so I thought I'd try writing my own. I am using ANTLRWorks, and I tried to generate graphs for the DFA, but there appear to be bugs in ANTLRWorks that prevent it. A: Grammars that are very large (many different tokens) have that problem, unfortunately (SQL grammars suffer from this too). Sometimes this can be fixed by making certain lexer rules fragments opposed to "full" lexer rules that produce tokens and/or re-arranging the way characters are matched inside the rules, but by looking at the way you already tried yourself, I doubt there can gained much in your case. However, if you're willing to post your lexer grammar here on SO, I, or someone else, might see something that could be changed. In general, this problem is fixed by splitting the lexer grammar into 2 or more separate lexer grammars and then importing those in one "master" grammar. In ANTLR terms, these are called composite grammars. See this ANTLR Wiki page about them: http://www.antlr.org/wiki/display/ANTLR3/Composite+Grammars EDIT As @Gunther rightfully mentioned in the comment beneath the OP, see the Q&A: Why my antlr lexer java class is "code too large"? where a small change (the removal of a certain predicate) caused this "code too large"-error to disappear. A: Well, actually it is not always easy to make a composite grammar. In many cases this AntTask helps to fix this problem (it must be run every time after recompiling a grammar, but this process is not so boring). Unfortunately, even this magic script doesn't help in some complex cases. Compiler can begin to complaining about too large blocks of DFA transitions (static String[] fields). I found an easy way to solve it, by moving (using IDE refactoring features) such fields to another class with arbitrarily generated name. It always helps when moving just one or more fields in such way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517438", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to automate Windows authentication in Python with selenium-rc? I am using python to write selenium-rc test code for my server code. The server application is written with ASP.NET and is configured with "Windows authentication". The execution steps of my python code look like the following: * *Start python main() *Create the selenium instance (say sel) *Start the selenium by calling sel.start() *Open the target URL with the selenium instance via calling sel.open(url) *Windows authentication dialog box pops up at this time *sel.open(url) is, by default, set to time out in 30 seconds while the authentication process is pending for input of username and password. *At this point, I could not find any way through selenium-rc interface to make it recognize the pop up dialog box. I google around and find out that the selenium-rc interface (in python) is for http authentication only- not Windows authentication. I have tried to use autoit within selenium but still without luck. Can any of you shed some light on this? Thanks in advance. marvinchen A: Selenium has issues recognizing that window (try to search HTTP Basic Authentification for more details about it) Basically, only thing which kinda works is to put username and password into URL request itself. Assuming your application runs on http://example.com the new url should look like this: http://username:password@example.com This solution works for me, but only using Google Chrome as a default browser for testing A: There is now way you can sort it out easy and at this point unless I have missed something last few months it will only be FireFox who can fix this for you. Read this blog how to sort it out: http://applicationtestingtips.wordpress.com/2009/12/21/seleniumrc-handle-windows-authentication-firefox/
{ "language": "en", "url": "https://stackoverflow.com/questions/7517441", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Eclipse android phonegap config.xml not working? I can't for the life of me figure out why my XML file isn't working. It's located in my assets www folder: The links to the images are correct - the id of my application is the same, but it still won't show my splash screen OR icon! Help! <?xml version="1.0" encoding="UTF-8"?> <widget xmlns = "http://www.w3.org/ns/widgets" xmlns:gap = "http://phonegap.com/ns/1.0" id = "com.phonegap.helloword" version = "1.0.0"> <name>Testerm Application</name> <description> A test application for PhoneGap </description> <author href="graemeleighfield@infinitegroup.co.uk" email="graemeleighfield@infinitegroup.co.uk"> Graeme Leighfield </author> <icon src="img/icon.png" width="72" height="72" ></icon> <gap:spalsh src="img/ash.jpg"/> <feature name="http://api.phonegap.com/1.0/geolocation"/> <feature name="http://api.phonegap.com/1.0/network"/> </widget> A: Yes the config.xml is only for build.phonegap.com. For building with Eclipse: Create a slash screen with splash.png filename in the res/drawable-hdpi folder. Add super.setIntegerProperty("splashscreen", R.drawable.splash) to your App.java file. public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.setIntegerProperty("splashscreen", R.drawable.splash); super.loadUrl("file:///android_asset/www/index.html"); } A: Graeme, are you building localy in eclipse? If yes, then config.xml and shouldnt' work at all -- it's for http://build.phonegap.com only -- not for your local development.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Help getting first web2py Cron Task working I'm running web2py locally with Windows 7 and live on a Linux Ubuntu server and I haven't been able to get my cron job to run in either. My crontab looks like this: */1 * * * * root *autoemail/send_autoemails and my function works fine when called manually. It also ends with db.commit() Other than that I don't know what else to do get it working although I really didn't understand all of the web2py book section on Cron, specifically when it came to soft/hard/external cron and all of that. I saw a web2py thread that perhaps cron was going to be replaced? Perhaps that has something to do with this? Is there something else I need to do to configure cron before it will work? Any ideas about how I can troubleshoot this are greatly appreciated. A: On this moment web2py is changing from Cron to Scheduler, with newer web2py versions Cron is disabled by default. You can use your function with the Scheduler, putting it into a model file and passing it to the scheduler creator class, in order to enable a new Scheduler instance with it: # New File applications/yourapp/models/zfunctions.py # def send_autoemails(): ... ...#Your code here ... ... from gluon.scheduler import Scheduler Scheduler(db,dict(yourfunction=send_autoemails)) After that you can add a new job simply from the web2py db admin interface, under db.task_scheduled you must click on insert new task_scheduled and set period to run, repeats, timeouts, enable, disable, etc.... Here are some info about it: http://web2py.com/book/default/chapter/04#Scheduler-(experimental)
{ "language": "en", "url": "https://stackoverflow.com/questions/7517444", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: .htaccess Redirect images folder to another domain ok so i have 2 domains site1.com/images/ (all images) and I need to redirect the imgages link site1.com/images/ to site2.com/images/ so that when and when exp. site1.com/images/i.jpg is called it will look at site2.com/images/1.jpg and will find it. .this is basic duplicate of the site and i don't want to move images back and forward. A: Put in your .htaccess on site1.com Redirect permanent /images http://sites2.com/images A: If the websites are on the same server and running under the same user, you could use symbolic links between both websites. E.g., create a symlink to /home/site2/public_html/images in /home/site1/public_html/images. Another option is using the Apache's Alias directive: Alias /images /home/site2/public_html/images Put this in the vhost config of site1. Using redirection on Apache: RedirectPermanent /images http://site2.example.com/images The best way would probably fixing the HTML code pointing to one domain. If you cannot decide which domain should get the static content, create a subdomain (or even a different domain) to store the files.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517445", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Xcode support of lambda functions I have a program coded in VS that I'm trying to port over to Xcode. There are several issues I have ran into including use of lambda functions. Since Xcode uses gcc 4.2 and thus doesn't support C++11, will I not be able to use any lambda functions? If I want to work on the code from my laptop without rewriting much of the code, will I have to install gcc 4.6 and compile using the terminal? A: You have few options: * *Re-write your code to the C++ 2003 standard. *Install GCC that supports C++11 features being used in the code and not use Xcode (you may use other IDEs, for example QtCreator or Eclipse CDT). *Wait for Xcode that comes with LLVM C++ compiler that supports C++11 features.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517449", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: C# Remove items from class array Possible Duplicate: Remove element of a regular array I have a method defined which returns class array. ex: Sampleclass[] The Sampleclass has properties Name, Address, City, Zip. On the client side I wanted to loop through the array and remove unwanted items. I am able to loop thru, but not sure how to remove the item. for (int i = 0; i < Sampleclass.Length; i++) { if (Sampleclass[i].Address.Contains("")) { **// How to remove ??** } } A: Arrays are fixed size and don't allow you to remove items once allocated - for this you can use List<T> instead. Alternatively you could use Linq to filter and project to a new array: var filteredSampleArray = Sampleclass.Where( x => !x.Address.Contains(someString)) .ToArray(); A: It's not possible to remove from an array in this fashion. Arrays are statically allocated collections who's size doesn't change. You need to use a collection like List<T> instead. With List<T> you could do the following var i = 0; while (i < Sampleclass.Count) { if (Sampleclass[i].Address.Contains("")) { Sampleclass.RemoveAt(i); } else { i++; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7517450", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Opening users twitter page in the twitter app from a button press in Android I have searched quite a lot on Stack Overflow for this request however it all seems to be centred around just opening the twitter client. I would like to click a button, open the default or used Twitter App and have it display someones profile. They then interact and click to follow if needed, however the main idea is getting the button to open the twitter app and being directed to the page in question. I have made a simple button that goes to the persons twitter page in the browser but i would like it to be more professional. Is this possible? Paul A: old but might do what you want another page that should help last but not least
{ "language": "en", "url": "https://stackoverflow.com/questions/7517451", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: [GLSL]How to compare the z value of all the vertices in world coordinate? This might be a simple question. As a newbie on GLSL, I would rather ask here. Now, in the vertex shader, I can get the position in world coordinate system in the following way: gl_Position = ftransform(); posWorld = gl_ModelViewMatrix * gl_Vertex; The question is: now can I can the max/min value of the posWorld among all the vertices? So that I can get a range of the vertex depth, but not the range of depth buffer. If this is not possible, how can I get the z value of near/far plane in world coordinate system? with best regards, Jian A: Yes it is possible with OpenGL. I'm doing a similar technique for calculating object's bounding box on GPU. Here are the steps: * *Arrange a render-buffer of size 1x1 type RGBA_32F in its own FBO. Set as a render target (no depth/stencil, just a single color plane). It can be a pixel of a bigger texture, in which case you'll need to setup the viewport correctly. *Clear with basic value. For 'min' it will be some huge number, for 'max' it's negative huge. *Set up the blending function 'min' or 'max' correspondingly with coefficients (1,1). *Draw your mesh with a shader that produces a point with (0,0,0,1) coordinate. Output the color containing your original vertex world position. You can go further optimizing from here. For example, you can get both 'min' and 'max' in one draw call by utilizing the geometry shader and negating the position for one of the output pixels. A: From what i know, i think this needs to be done manually with an algorithm based on parallel reduction. I would like someone to confirm if there exists or not an OpenGL or GLSL function that already does this. on the other hand, you can have access to the normalized near/far planes within a fragment shader, http://www.opengl.org/wiki/GLSL_Predefined_Variables#Fragment_shader_uniforms. and with the help of some uniform variables you can get the world far/near.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517455", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What's a recommended way to build a HTML5 mobile app? Although we are new to this technology, we are working on a HTML5 mobile app nowadays with sencha-touch and some other js libs like i18n. The problems are that: * *No matter how much we try to tune the performance, it feels kinda slow. *Every time we change to another page, when the browsers are loading the next page, there is a ugly blank-paged interval. We think we might miss some structural and best practices here with HTML5 mobile app. We speculate that we are still treating HTML5 mobile app with our web logic. That's why I would like to ask: * *Is it okay to add in some other js except for sencha-touch? Is it the thing that drags the speed here? *Is a multi-paged mobile app a good practice? Or should we build everything within the same html page? *Is there a way to pre-load everything so that the page change can be faster? Thanks A: I personally use JQuery Mobile. http://jquerymobile.com/ The framework does take some time to understand. It's full version should be released this month or early next month. I have been working with it since Alpha. If you are familiar with JQuery I highly recommend it. They are taking care of some of the really simple things such as the varying differences between every phone. Here is a support platform list: http://jquerymobile.com/gbs/ It is ajax driven, but this feature can be turned off. It can be a little heavy, but considering the amount of work it does to take care of so many odds things on every phone, it really is worth learning it in my opinion. I would recommend going through the docs & demos to see if this is what you are looking for. http://jquerymobile.com/demos/1.0b3/ If you have any specific questions about it, feel free to ask. A: Sencha touch has good performance, also they promise even greater performance in the upcoming (around October 26th) sencha touch 2 (http://www.sencha.com/blog/sencha-touch-2-what-to-expect). So the sencha touch as a JS library is well optimized. Maybe you are app is not well optimized or something else is slowing it down. All in all, my point is that sencha touch as a JS library is arguably as good as JS library could get, so it isn't the problem at all. All JS applications should be one page HTML. There are ways how to maintain the browser history and state, if that's your concern. There are couple of ways to pre-load and cache everything, but if you do the one page HTML web app then you don't really have to. So my advice is to stick with sencha touch, at least until the sencha touch 2 comes out, and see if the performance issues are solved, before moving to other solutions. Also first thing you need to do is to make it a single HTML page app and do some testing and measuring to see what is slowing the app down.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517460", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Mod Rewrite 500 Error Correction I have a .htaccess file that is using Mod_Rewrite but I am running into a problem if someone puts in junk in the URL it generates a 500 error, and displays all my mod information. I would like to either stop it from generating the 500 error or forward that error to a different page. I have tried. Error Document 500 /index.php ...but it does not work or redirect. Here is my full .htaccess Options -Indexes Options +FollowSymlinks ErrorDocument 500 /index.php RewriteEngine On RewriteRule ^BEARS bears.php?page=bears [NC,L] RewriteCond %{http_host} ^www.domian.org/login.php [NC] RewriteRule ^(.*)$ https://www.domian.org/login.php [R=301,L] RewriteCond %{http_host} ^domian.com [NC] RewriteRule ^(.*)$ http://www.domian.org/$1 [R=301,L] RewriteCond %{http_host} ^domian.org [NC] RewriteRule ^(.*)$ http://www.domian.org/$1 [R=301,L] RewriteCond %{http_host} ^www.domian.com [NC] RewriteRule ^(.*)$ http://www.domian.org/$1 [R=301,L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.+)/DB/(.+)/page/(.+)$ $1.php?DB=$2&page=$3 [L,QSA] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.+)/DB/(.+)$ $1.php?DB=$2 [L,QSA] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.+)/(.+)$ $1.php?page=$2 [L,QSA] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.+)$ $1.php?page=$1 [L,QSA] Also does anyone know where the 500 error is being generated from. I know the error folder has the error documents in there, but this error says "Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request" , and I cannot find where this is pulling from. [Thu Sep 22 11:11:40 2011] [debug] core.c(3071): [client 74.84.118.99] redirected from r->uri = /test.html.php.php.php.php.php.php.php.php.php [Thu Sep 22 11:11:40 2011] [debug] core.c(3071): [client 74.84.118.99] redirected from r->uri = /test.html.php.php.php.php.php.php.php.php [Thu Sep 22 11:11:40 2011] [debug] core.c(3071): [client 74.84.118.99] redirected from r->uri = /test.html.php.php.php.php.php.php.php [Thu Sep 22 11:11:40 2011] [debug] core.c(3071): [client 74.84.118.99] redirected from r->uri = /test.html.php.php.php.php.php.php [Thu Sep 22 11:11:40 2011] [debug] core.c(3071): [client 74.84.118.99] redirected from r->uri = /test.html.php.php.php.php.php [Thu Sep 22 11:11:40 2011] [debug] core.c(3071): [client 74.84.118.99] redirected from r->uri = /test.html.php.php.php.php [Thu Sep 22 11:11:40 2011] [debug] core.c(3071): [client 74.84.118.99] redirected from r->uri = /test.html.php.php.php [Thu Sep 22 11:11:40 2011] [debug] core.c(3071): [client 74.84.118.99] redirected from r->uri = /test.html.php.php [Thu Sep 22 11:11:40 2011] [debug] core.c(3071): [client 74.84.118.99] redirected from r->uri = /test.html.php [Thu Sep 22 11:11:40 2011] [debug] core.c(3071): [client 74.84.118.99] redirected from r->uri = /test.html Where is this loop happening? Not seeing it. A: I figured I would put the problem solution here just in case someone comes across the same issue. My problem code was this snippet... RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.+)$ $1.php?page=$1 [L,QSA] Seems that a junk entry will cause this too loop like crazy. A: To expand on your answer, it is more specifically this line: RewriteRule ^(.+)$ $1.php?page=$1 [L,QSA] which does not check to see if the filename already ends with PHP. It loops around, adding .php.php.php.php until the max is reached (check apache/logs/error.log) and then just serves the original page, which happens to be present, so it looks like everything's ok. To fix this, add something like this: RewriteRule ^(.*)\.php$ - [L] which stops ([L]) if the address ends with .php.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517470", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: problem with collision of UIImageViews -(void)moveTheImage{ for (NSUInteger i = 0; i < [views count]; i++) { image = [views objectAtIndex:i]; X = [[XArray objectAtIndex:i] floatValue]; Y = [[YArray objectAtIndex:i] floatValue]; image.center=CGPointMake(image.center.x + X, image.center.y + Y); if(!intersectFlag) { if(CGRectIntersectsRect(image.frame,centre.frame)) { intersectFlag = YES; label.text= [NSString stringWithFormat:@"%d", count]; ++count; } } else { if(!CGRectIntersectsRect(image.frame,centre.frame)) { intersectFlag = NO; } } } I would like that every time "image" intersect with "centre" the count increase of 1 but when there is a collision the count grows very fast until "image" doesn't touch "centre". More precisely "image" moves an then pass through "centre" and the count grows and when "image" is not in contact with "centre" the counter stops.How cn I solve this please? sorry for my english I'm french :/ A: As I said on the last comment, I think your count problem comes because of the frame rate. So you can use an NSMutableSet which will contain all the objects being in collision. In the interface, you declare your new set: NSMutableSet * collisionObjects; In the init method: collisionObjects = [[NSMutableSet alloc] init]; In the dealloc: [collisionObjects release]; And your method becomes: -(void)moveTheImage{ for (NSUInteger i = 0; i < [views count]; i++) { image = [views objectAtIndex:i]; X = [[XArray objectAtIndex:i] floatValue]; Y = [[YArray objectAtIndex:i] floatValue]; image.center=CGPointMake(image.center.x + X, image.center.y + Y); if (CGRectIntersectsRect(image.frame,centre.frame)) { // If the object is in collision, we add it to our set // If it was already in it, it does nothing [collisionObjects addObject:image]; } else { // If the object is not in collision we remove it, // just in case it was in collision last time. // If it was not, it does nothing. [collisionObjects removeObject:image]; } } // The intersectFlag is updated : YES if the set is empty, NO otherwise. intersectFlag = [collisionObjects count] > 0; // We display the count of objects in collision label.text= [NSString stringWithFormat:@"%d", [collisionObjects count]]; } And this way you always have the count of your objects in collision using [collisionObjects count].
{ "language": "en", "url": "https://stackoverflow.com/questions/7517472", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: accessing 64-bit COM server from managed assembly fails I have a problem accessing a COM object from a 64-bit COM server written in C++ from a .NET project (the 32-bit version works well). It is a problem similar to the one described here Troubleshooting an x64 com interop marshaling issue. I have a COM method that takes as parameter an array of structures with longs and BSTRs. When the call returns it works OK if the call was made from a native module, but when it was made from a managed (C#) assembly, I get an access violation. If the strings are not populated in the struct then there is no exception. The proxy/stub file start with the following: 32-bit /* File created by MIDL compiler version 7.00.0500 */ /* at Thu Sep 22 17:52:25 2011 */ /* Compiler settings for .\RAC.idl: Oicf, W1, Zp8, env=Win32 (32b run) protocol : dce , ms_ext, c_ext, robust error checks: allocation ref bounds_check enum stub_data VC __declspec() decoration level: __declspec(uuid()), __declspec(selectany), __declspec(novtable) DECLSPEC_UUID(), MIDL_INTERFACE() */ //@@MIDL_FILE_HEADING( ) #if !defined(_M_IA64) && !defined(_M_AMD64) 64-bit /* File created by MIDL compiler version 7.00.0500 */ /* at Thu Sep 22 17:58:46 2011 */ /* Compiler settings for .\RAC.idl: Oicf, W1, Zp8, env=Win64 (32b run) protocol : dce , ms_ext, c_ext, robust error checks: allocation ref bounds_check enum stub_data VC __declspec() decoration level: __declspec(uuid()), __declspec(selectany), __declspec(novtable) DECLSPEC_UUID(), MIDL_INTERFACE() */ //@@MIDL_FILE_HEADING( ) #if defined(_M_AMD64) I tried both with the 32-bit and 64-bit version of midl.exe from Windows SDK v7.0A, but it generates the very same output. So the suggestion from the other thread didn't help. Any other ideas? UPDATE: The struct looks like this (I changed the names, the rest is identical): [uuid(6F13C84D-0E01-48cd-BFD4-F7071A32B49F)] struct S { long a; BSTR b; long c; BSTR d; long e; BSTR f; BSTR g; BSTR h; BSTR i; long j; BSTR k; long l; BSTR m; long n; }; The method signature looks like this: [id(54)] HRESULT GetListOfStructs(SAFEARRAY(struct S)* arrRes); I actually have several such structs and methods like this. Obviously, all of them have the same problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517474", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Invoke main method in java class from jsp? I had a requirement to create a small file utility class to run off the command line from a windows desktop. The code got completed, however, after reviewing how to package it, it requires a custom framework from the main application in order to run. Don't ask why as that would take a while to answer, just take this as a valid assumption. In any event, now they want a jsp to call this class, but they still want it to be more of a separate utility, even though it's part of the main codebase. They also want it to call the main method in the utility, which doesn't sound like good design to me, but they didn't want to change it to a servlet class. The program just takes in some arguments and then it's basically on one step operation on the files, then it finishes. Not really a jsp type request/response scenario, but I'm not the one writing the requirements. From a design perspective, is there a better way to do this for a simple utility application? Thanks, James A: If you really can't change the design, you could either just import the class and invoke it (this works only if it's in the webapp's classpath). YourMainClass.main(new String[] {"some", "arguments"}); Or spawn a process and execute it (this is really not recommended as the new process would allocate another bunch of memory which is as much as the server is currently using!). Runtime.getRuntime().exec("java -cp /path/to/root com.example.YourMainClass some arguments"); Both ways can be done in a scriptlet (yuck), or preferably just in a Servlet. A: Have the main method call a service/library method. The JSP can call the same service/library method. There's no need to explicitly call main; make it clean from the beginning. A: T**his is my JavaMail.java** It is java class Which Contain a Main Method... Public Class JavaMAil{ String d_email = "abc@gmail.com",//you email address d_password = "XXXX", //your email password d_host = "smtp.gmail.com", d_port = "465", m_to = "xyz@gmail.com ", // Target email address m_subject = "Testing", m_text = "Hey, this is a test email."; public JavaMail() { Properties props = new Properties(); props.put("mail.smtp.user", d_email); props.put("mail.smtp.host", d_host); props.put("mail.smtp.port", d_port); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.auth", "true"); //props.put("mail.smtp.debug", "true"); props.put("mail.smtp.socketFactory.port", d_port); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); try { SMTPAuthenticator auth = new SMTPAuthenticator(); Session session = Session.getInstance(props, auth); MimeMessage msg = new MimeMessage(session); msg.setText(m_text); msg.setSubject(m_subject); msg.setFrom(new InternetAddress(d_email)); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to)); Transport.send(msg); } catch (Exception mex) { mex.printStackTrace(); } } public static void main(String[] args) { JavaMail blah = new JavaMail(); } private class SMTPAuthenticator extends javax.mail.Authenticator { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(d_email, d_password); } } } **This is my mail.jsp** And It is jsp it Invokes Main method from the class called JavaMail <%@ page import="mail.JavaMail" %> <% JavaMail obj = new JavaMail(); %>
{ "language": "en", "url": "https://stackoverflow.com/questions/7517476", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C++ System Time returning the same wrong value I want to retrieve the last write date on a file. I have written this code for it, but it returns me 52428 in values like "Year" all the time int LastErrorCode; LPCSTR Path = "C:/Users/Username/Desktop/Picture.PNG"; WIN32_FIND_DATA Information; if(!FindFirstFile(Path, &Information)) { int LastErrorCode = GetLastError(); cout << "FIND FIRST FILE FAILED" << endl; cout << LastErrorCode << endl; } SYSTEMTIME MyTime; FILETIME MyFileTime = Information.ftLastWriteTime; if(!FileTimeToSystemTime(&MyFileTime, &MyTime)) { LastErrorCode = GetLastError(); cout << "FILE TIME TO SYSTEM TIME FAILED" << endl; cout << LastErrorCode << endl; } cout << MyTime.wYear << endl; A: The hex value for 52428 is 0xCCCC, which seems to indicate it has not been initialized. The function call is probably failing. Check the return codes from FindFirstFile and FileTimeToSystemTime (and then call GetLastError after a failure to find the error code). Edit Based on the edits to the OP, the FindFirstFile call is likely the one that is failing. The return value is a handle (not a zero/non-zero result). The code should assign the result to a variable of type HANDLE and then compare against INVALID_HANDLE_VALUE. Note too that after a successful call to FindFirstFile, the code should have a corresponding call to FindClose with the handle to avoid leaking resources. A: Please check the documentation of this function! It tells you the following: If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error information, call GetLastError. Try to check if the return value is nonzero, if it's not, try calling getlasterror and print that error message on the console and provide this information. A: In the past, I have used WIN32_FILE_ATTRIBUTE_DATA instead of WIN32_FIND_DATA. Then to get the file's information, I use GetFileAttributesEx. An example is below: string strFile = "c:\\myfile.txt"; WIN32_FILE_ATTRIBUTE_DATA fileInfo; // Get the attributes structure of the file if ( GetFileAttributesEx(strFile, 0, &fileInfo) ) { SYSTEMTIME stSystemTime; // Convert the last access time to SYSTEMTIME structure: if ( FileTimeToSystemTime(&fileInfo.ftLastAccessTime, &stSystemTime) ) { printf("Year = %d, Month = %d, Day = %d, Hour = %d, Minute = %d\n", stSystemTime.wYear, stSystemTime.wMonth, stSystemTime.wDay, stSystemTime.wHour, stSystemTime.wMinute); } A: Shouldn't you use backslashes '\' in file path? Provided that this would correct your file path, the FindFirstFile API call might possibly succeed and would get you the time you needed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517479", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: RESTSharp 102 & Async+WP7.1 The newer 102 version broke my requests :( this doesnt work anymove ... client.ExecuteAsync<Resource>(request, (response) => { var resource = response.Data; }); has anyone figured out how to use now? documentation is old :( A: The updated version as of 102.1 for wp7 looks like this. // async with deserialization var asyncHandle = client.ExecuteAsync(request, response => { Console.WriteLine(response.Data.Name); }); and yes it is now updated on the site coincidentally under the account of the same name as the guy in the comments. @John Sheehan thanks for RestSharp https://github.com/johnsheehan/RestSharp
{ "language": "en", "url": "https://stackoverflow.com/questions/7517484", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why does OBJECT require an explicit end tag? In the following example, the word "Goodbye" doesn't render (in Chrome 14, anyway): <html> <body> <p>Hello</p> <object width="400" height="400" data="helloworld.swf"/> <p>Goodbye</p> </body> </html> However, it does render when I add an explicit end tag to object: <html> <body> <p>Hello</p> <object width="400" height="400" data="helloworld.swf"></object> <p>Goodbye</p> </body> </html> Since I'm not supplying any parameters to my object and I don't want anything to show up if the object fails to load, it seems like the first syntax should be allowed. Is anyone aware of a specific reason why this is disallowed? A: Because object should contain fallback content in case the browser doesn't support, or doesn't have access to a plugin which supports, the content the object element references. A: Because it is specified to be that way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517487", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to get different string from a file in xcode 4? In my prgram, I want to use a txt file to store all the words that I need to use. Here is the example of the txt file: AAA BBB CCC DDD If I want to get a specific word (such as CCC) in the txt file, could it be possible for me to do so in xocde 4? If yes, how to program? Thank you so much A: xcode has nothing to do with this. Write your code in whatever language you are confident with. I did suggest use a hashmap or dictionary or hashtable for storing the words as keys. This way querying for the words would be lightning quick....
{ "language": "en", "url": "https://stackoverflow.com/questions/7517490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HTTPS AppStrip code? Does anyone working with AppStrip have a code to call the AppStrip bar via HTTPS? I'm hoping to have something up to test next week before the Oct. 1 migration deadline, but they haven't updated their site with the code yet. Last I heard something was supposed to be up this week. Thanks! A: AppStrip has update the code on their web site. In the interest of not disclosing their code outside of the partners they accept, I won't post it here, but if you are using the AppStrip bar you can find it on their web site. Log in to AppStrip.com, choose 'Applications', click 'Code' next to one of your applications in the list, and you will see that the codes have been updated to be compliant with the SSL migration.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517491", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Designing keyboard on J2ME color mobile I want to create a J2ME application for writing SMS faster using QWERTY button on a simple non-qwerty phone. So the application will show all these buttons which user can use I've knowledge on Java and have developed simple calculator too but cant design it in NetBeans. So looking for help [only to design the interface,] This app will run on a simple phone with [1-abc] [2-def] keypad A: Well, technically your idea looks doable - at least if device screen is large enough to handle 4 rows of your pseudo-buttons plus at least one row for SMS text. And it doesn't even look very difficult - in this sense your idea looks good to me. In MIDP lcdui package, classes Canvas, Graphics and Font seem to have all the stuff one would need to do that. * *Yeah that would make a good exercise in mobile UI. On the other hand, I wouldn't bet on such a design being more convenient for users compared to say, plain lcdui TextBox which simply utilizes platform-specific key entries whatever they are.   Just think of it... On smaller screen devices, TextBox will give users much larger area to view text - just because your design will occupy quite a lot of screen space with the "keypad". On large screen devices, your chances are even worse because these tend to have virtual or even real qwerty and this one will most likely be utilized by TextBox which will be as good if not better than yours. As for writing SMS faster you mention, I am not that certain that there will be sufficient speed up to make it appealing for users - even in the case of "competing" against [1-abc] [2-def] keypad. * *Let's see... what would it take for user to print word "SMS"... * *On your keypad: Select-button for S. Up-right-Select for M. Left-down-select for S. 5 buttons, 7 presses. *On phone keypad: 4 presses on [7-pqrs] for S. 1 press on [6-mno] for M. 4 presses on [7-pqrs] for S. 3 buttons, 9 presses.   Not much difference I'm afraid.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517495", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Sleep / Suspend / Hibernate Windows PC I'd like to write a short python script that puts my computer to sleep. I'Ve already searched the API but the only result on suspend has to do with delayed execution. What function does the trick ? A: Without resorting to shell execution, if you have pywin32 and ctypes: import ctypes import win32api import win32security def suspend(hibernate=False): """Puts Windows to Suspend/Sleep/Standby or Hibernate. Parameters ---------- hibernate: bool, default False If False (default), system will enter Suspend/Sleep/Standby state. If True, system will Hibernate, but only if Hibernate is enabled in the system settings. If it's not, system will Sleep. Example: -------- >>> suspend() """ # Enable the SeShutdown privilege (which must be present in your # token in the first place) priv_flags = (win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY) hToken = win32security.OpenProcessToken( win32api.GetCurrentProcess(), priv_flags ) priv_id = win32security.LookupPrivilegeValue( None, win32security.SE_SHUTDOWN_NAME ) old_privs = win32security.AdjustTokenPrivileges( hToken, 0, [(priv_id, win32security.SE_PRIVILEGE_ENABLED)] ) if (win32api.GetPwrCapabilities()['HiberFilePresent'] == False and hibernate == True): import warnings warnings.warn("Hibernate isn't available. Suspending.") try: ctypes.windll.powrprof.SetSuspendState(not hibernate, True, False) except: # True=> Standby; False=> Hibernate # https://msdn.microsoft.com/pt-br/library/windows/desktop/aa373206(v=vs.85).aspx # says the second parameter has no effect. # ctypes.windll.kernel32.SetSystemPowerState(not hibernate, True) win32api.SetSystemPowerState(not hibernate, True) # Restore previous privileges win32security.AdjustTokenPrivileges( hToken, 0, old_privs ) If you want just a one-liner with pywin32 and has the right permissions already (for a simple, personal script): import win32api win32api.SetSystemPowerState(True, True) # <- if you want to Suspend win32api.SetSystemPowerState(False, True) # <- if you want to Hibernate Note: if your system has disabled hibernation, it will suspend. In the first function I included a check to at least warn of this. A: Get pywin32, it also contains win32security if I remember correctly. Then try the mentioned script again. A: import os os.system(r'rundll32.exe powrprof.dll,SetSuspendState Hibernate') A: I don't know how to sleep. But I know how to Hibernate (on Windows). Perhaps that is enough? shutdown.exe is your friend! Run it from the command prompt. To see its options do shutdown.exe /? I believe a hibernate call would be: shutdown.exe /h So, putting it all together in python: import os os.system("shutdown.exe /h") But as other have mentioned, it is bad to use os.system. Use the popen instead. But, if you're lazy like me and its a little script them meh! os.system it is for me. A: If you're using Windows, see this gmane.comp.python.windows newsgroup post by Tim Golden. A: subprocess.call(['osascript', '-e','tell app "System Events" to sleep'])
{ "language": "en", "url": "https://stackoverflow.com/questions/7517496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: HSBC CPI problem from ASP We have been using the HSBC payment component for a while, running on a windows 2003 r2 sp1 box, however we now have to move it to a 2003 r2 sp2 box (both 23 bit) We have registered the CcCpiTools.dll and set permissions on the Dll’s to Everyone and added it to the system32 folder (with its CcCpiTools.dll), but for some reason get the Error “ActiveX component can't create object: 'CcCpiCOM.OrderHash'” Would anyone know why we are getting this, are there any new security features in 2003 sp2 that’s blocking the dll being executed from ASP? The website is set to allow execute permission Any help would be very much appreciated. A: You might have possibly missed to install a dependent library - check the original locations running application with DependencyViewer. I remember there was a separate KB install for a DLL that hosted unmanaged encryption and hashing algorithms - search MSDN for CAPICOM.DLL.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517500", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: String address to location on Google Maps I have a map view in my android app, i'm just wondering if it's possible to have a function which takes in a String which would contain an address that would be passed onto google maps and returned as a geopoint location on the map? If anyone knows where any tutorials are on how to do this, can you please point me to it? A: Take a look at the Geocoder class, which you can pass an address string and it will return a list of actual addresses for the specified string. http://developer.android.com/reference/android/location/Geocoder.html Take a look at getFromLocationName(String locationName, int maxResults)
{ "language": "en", "url": "https://stackoverflow.com/questions/7517501", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: .net - dependentAssembly Today I was getting some assembly mismatch issue and after a bit of digging I found that for a particular DLL, actual reference in project was made to some other version and config file for that project was showing dependency to some other version of the same DLL. Exp. <dependentAssembly> <assemblyIdentity name="NHibernate" publicKeyToken="aa95f207798dfdb4" /> <bindingRedirect oldVersion="2.0.1.4000" newVersion="2.1.2.4000" /> </dependentAssembly> I removed the dependency declaration for that assembly from the config file and voila! I was able to run again :-) My question is - When are <dependentAssembly> declarations made in the project config file? Do we add them manually? And in what scenario? A: When are <dependentAssembly> declarations made in the project config file? Do we add them manually? And in what scenario? When you want to ensure the software binds to a newer version of an assembly at runtime than that which it was built against. More info: http://msdn.microsoft.com/en-us/library/7wd6ex19.aspx Can you please also guide in what scenario we need older version at compile time and newer version at run-time? For example, if you are using a vendor API, the vendor may have identified a bug and needs to issue a new version but you've already shipped.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517502", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Jetty Spring Web Services sqljdbc_auth.dll conflict We have created 2 web services from similar code bases that are using Spring and Hibernate and we are wanting to run them in a Jetty Server. Each Web server can initliaze the wsdl just fine from Spring. If I send a message to one web service that ends up connecting to a database it runs fine. As soon as I call the second web service it tries to connect to the database but fails. We are using hibernate and sql server's jdbc driver. The failure occurs when the second web service tries to use the sqljdbc_auth.dll. See below: 2011-09-22 10:28:41,873 WARNING [com.microsoft.sqlserver.jdbc.internals.AuthenticationJNI] - Failed to load the sqljdbc_auth.dll Is there a file locking issue with the dll? Where the first web service has a lock and the second one does not? A: Please copy sqljdbc_auth.dll file in to jdk bin folder, i.e. *C:\Program Files\Java\jdk1.6_32\bin*. Paste file in your server side where the JVM is running. If consuming web services please apply the same in client side as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517504", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iOS launch images file type I'm working on an iPad app and reading this page that said launch images must be in PNG format, but in their iOS Human Guidelines, they only recommend to use .png, not "a must". I want to use .jpg format as my launch images because my launch images size in .png are about 2 mb alone, and only 90 kb in .jpg format. Thanks A: You need to specify in the Info.plist the UILaunhImageFile field <key>UILaunchImageFile</key> <string>Default.jpg</string> Setting this information will make the system look for Default.jpg and all its variations (portait, landscape, @2x, etc) instead of .png for example, I'm coding an Universal app, and now all the launch images are .jpg, including iPad Retina: Default-Portrait@2x.jpg A: Yes, that's true. Even if you find some workaround (e.g. just renaming the jpeg file to "Default.png"), since it is documented that it must be PNG then Apple is free to make your workaround stop working at any time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517508", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Authorize Attribute MVC 3 & Web.Config AppSettings Value Does anyone know if there is a way of using a value in Web.Config AppSettings section on an Authorize attribute for a controller in MVC3? I am currently using something like this in web.config: <add key="AdminRole" value="Admins"/> , and then I tried pulling the into class and using the value on the Authorize attribute but .NET complains about the values not being constants, etc. I just want to be able to use a value set in web.config to filter Authorization so that different deployments can use variations of role names based on their system configurations. Any help would be appreciated, Thanks! A: Here's a working example: [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] public class AuthorizeByConfig : AuthorizeAttribute { /// <summary> /// Web.config appSetting key to get comma-delimited roles from /// </summary> public string RolesAppSettingKey { get; set; } /// <summary> /// Web.config appSetting key to get comma-delimited users from /// </summary> public string UsersAppSettingKey { get; set; } protected override bool AuthorizeCore(HttpContextBase httpContext) { if (!String.IsNullOrEmpty(RolesAppSettingKey)) { string roles = ConfigurationManager.AppSettings[RolesAppSettingKey]; if (!String.IsNullOrEmpty(roles)) { this.Roles = roles; } } if (!String.IsNullOrEmpty(UsersAppSettingKey)) { string users = ConfigurationManager.AppSettings[UsersAppSettingKey]; if (!String.IsNullOrEmpty(users)) { this.Users = users; } } return base.AuthorizeCore(httpContext); } } And decorate your controller class or method like so: [AuthorizeByConfig(RolesAppSettingKey = "Authorize.Roles", UsersAppSettingKey = "Authorize.Users")] Where Authorize.Roles and Authorize.Users are web.config appSettings. A: You would have to write your own AuthorizationAttribute class which at runtime reads the value from web.config. In .NET it is not possible to declare an attribute using runtime-dependent values.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517510", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Unable to connect to Lion server using finder, but able to using the lion server program? I have just set up a server at work. Its sits the other side of a substantial firewall and there for I VPN in to access it. The VPN appears to be functioning as I am able to access the server through the Lion server program and make server admin changes from at home. However I am unable to access the shared folders Which I am able to do easily at work n the network. Im a programmer and confess that I'm not the worlds best networker or server admin(everybody has to start somewhere). If anyone has had a similar problem please let me know. Much thanks GC A: case solved but don't ask me how. I tried accessing the shared files again and it worked. If you can explain that your a better man than me. Im going to put it down to a network issue. Thanks for your time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to use lazy values within for-expressions? I have a list of Chickens and Eggs I want to create. They are defined as: class Chicken (val name: String, e: => Egg) { lazy val child = e } class Egg (val name: String, c: => Chicken) { lazy val parent = c } and a single pair must be instantiated lazily because they contain circular references: def fillBarn { lazy val chicken: Chicken = new Chicken("abc", egg) lazy val egg: Egg = new Egg("def", chicken) } I have a list of chicken / egg names that I want to create. Unfortunately the following doesn't compile: val names = List("C1 E1", "C2 E2", "C3 E3") val list = for { Array(cn, en) <- names.map(_.split(" ")) lazy c: Chicken = new Chicken(cn, e) lazy e: Egg = new Egg(en, c) } yield (c, e) but it does without the sugar: val list = names.map(_.split(" ")).map { case Array(cn, en) => lazy val c: Chicken = new Chicken(cn, e) lazy val e: Egg = new Egg(en, c) (c, e) } Now arguably in this simple case it's nicer without the for-expression, but if I did want to use the for-expression, could I? I also realise that in this trivial case I could construct the Chicken and Egg instances within a yield block, but this won't generally be true, say if I wanted to do some extra filtering and mapping based on the instances. A: Well, in this (and arguably also in more advanced cases), you could always adapt the fillBarn method to give you exactly what you need (that’s the only way to make sense of this method anyway): def fillBarn(c: String, e: String) = { lazy val chicken: Chicken = new Chicken(c, egg) lazy val egg: Egg = new Egg(e, chicken) (chicken, egg) } and then val list = for { Array(cn, en) <- names.map(_.split(" ")) (c, e) = fillBarn(cn, en) } yield (c, e) Of course, if you want to, there is no need in defining the fillBarn method. You can also do it in-line: val list = for { Array(cn, en) <- names.map(_.split(" ")) (c, e) = { lazy val chicken: Chicken = new Chicken(cn, egg) lazy val egg: Egg = new Egg(en, chicken) (chicken, egg) } } yield (c, e) The general structure of a for statement in Scala is fixed. There is only the flatMap/map/foreach with <- or the direct assignment to a new variable name for later use with =. But on the right side of these statements you may put whatever you like inside a block as long as this block returns the appropriate object.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517515", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why is my MVC Action not model binding my collection? In my site I am gathering a list of numbers (for sorting) and sending them to my MVC action with the following code: $('#saveButton').click(function () { var configId = $('#ConfigId').val(); var steps = new Array(); $('#stepList li').each(function (index) { steps[index] = $(this).attr('stepId'); }); // Send the steps via ajax $.ajax({ url: '" + Url.Action(MVC.GrmDeployment.EditStep.Reorder()) + @"', type: 'POST', dataType: 'json', data: { configId: configId, stepIds: steps }, success: function (data) { if (data.success) { alert('Reorder was successful'); } else { alert(data.msg); } } }); }); Through chrome I see this sending the following data over the wire: configId:1 stepIds%5B%5D:3 stepIds%5B%5D:2 In my controller I have the following method to receive the values public virtual ActionResult Reorder(int configId, ICollection<int> stepIds) { } The problem is that the stepIds collection is null. Anyone see any reason why? A: Use JSON.Stringify: var viewModel = new Object(); viewModel.configId = $('#ConfigId').val(); viewModel.steps = new Array(); data: { JSON.Stringify(viewModel) }, A: As I recall, jQuery changed the way it encodes arrays in the ajax method, so in order to continue being compatible with MVC, you have to set the traditional option to true: $.ajax({ url: '@Url.Action(MVC.GrmDeployment.EditStep.Reorder())', type: 'POST', dataType: 'json', traditional: true, // This is required for certain complex objects to work with MVC AJAX. data: { configId: configId, stepIds: steps }, success: function (data) { if (data.success) { alert('Reorder was successful'); } else { alert(data.msg); } } }); A: I have had actions binding to arrays. I personally have an action with a string[] parameter. Try public virtual ActionResult Reorder(int configId, int[] stepIds) { }
{ "language": "en", "url": "https://stackoverflow.com/questions/7517516", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Control a frame from container page I have a web page that contains two textboxes and a button. I can't control this page by adding any thing to it, or changing any thing in it. I want to (in some way) write some text in the first textbox when the page loads, without pressing the button. I want to put the page in a frame and then control it from the container page I know that I have to use jquery but I need a sample that explain that or to tell me how to do what I want For example, if I have the file "a.htm": The content of "a.htm": <iframe id="frame1" src="f.htm" /> and the content of "f.htm" is: <input type="textbox" id="tbx1" /> <input type="textbox" id="tbx2" /> <input type="submit" id="okbtn" value="ok"/> For example, when the page "a.htm" loads, I want the textbox ("tbx1" for example) in the page "f.htm", (contained in the frame "frame1") to be filled by some text. thanks in advance A: Before I start on this answer, it's worth explaining that you cannot use JavaScript alone to manipulate a frame which serves content from a separate domain*. In other words, if your page, a.htm, is on your domain (e.g. http://yourdomain.com/a.htm), and f.htm is on another domain (e.g. http://someothersite.com/f.htm), then JS will not be able to access anything inside the iframe. *There are techniques available to do this, but as a rule of thumb they cause more trouble than good. However, if it's all on the same domain you should have no trouble. In a.htm, to access the iframe, you could use the following jQuery snippet: $(function() { var iframe = $('#frame1').load(function() { $(this).contents().find('#tbx1').val('Text in a box!'); }); }); So, your a.htm could look like: <html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script> <script type="text/javascript"> $(function() { var iframe = $('#frame1').load(function() { $(this).contents().find('#tbx1').val('Text in a box!'); }); }); </script> </head> <body> <iframe id="frame1" src="f.htm" /> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/7517517", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using Jquery, replace one row in table with a new one Say I have a table: <table id="mytable"> <tr class="old_row"><td>1</td><td>2</td><td class="edit">Edit</td></tr> <tr class="old_row"><td>1</td><td>2</td><td class="edit">Edit</td></tr> <tr class="old_row"><td>1</td><td>2</td><td class="edit">Edit</td></tr> </table> I want to click on the <td>Edit</td> cell and use jquery to replace the entire row with a new row with more content, e.g. $(document).ready(function() { $('#mytable .edit').click( function() { var tr = $(this).parent(); var new_row = '<tr class="new_row"><td>3</td><td>4</td><td>Save</td></tr>' // code to replace this row with the new_row }); } ); Any idea how this could be done? A: Use jQuery.replaceWith() $(document).ready(function() { $('#mytable .edit').click( function() { var tr = $(this).parent(); var new_row = '<tr class="new_row"><td>3</td><td>4</td><td>Save</td></tr>'; tr.replaceWith(new_row); }); }); A: $(document).ready(function() { $('#mytable .edit').click( function() { var new_row = '<tr class="new_row"><td>3</td><td>4</td><td>Save</td></tr>' $(this).parent().replaceWith(new_row); }); } ); A: jQuery's replaceWith(). Example: $(document).ready(function() { $('#mytable .edit').click( function() { var tr = $(this).parent(); var new_row = '<tr class="new_row"><td>3</td><td>4</td><td>Save</td></tr>' tr.replaceWith(new_row); // code to replace this row with the new_row }); } ); A: http://jsfiddle.net/hAvyv/ $('.edit').click(function(){ $(this).parent().removeClass('old_row').addClass('new_row').html('<td>3</td><td>4</td><td>Save</td>'); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7517519", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: How to play two different sounds in iPhone sdk? I have two different wav files which I have to play by calling different methods. I can play one wav file but unable to play the one. My code is In .h AVAudioPlayer *player1, *player2; In .m -(void)correctSound { NSString *sound = [[NSString alloc] initWithFormat:@"claps2"]; NSLog(@"sound claps %@", sound); NSURL *url = [[NSURL alloc] initFileURLWithPath:[[NSBundle mainBundle] pathForResource:sound ofType:@"wav"]]; NSLog(@"claps url %@", url); player1 = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil]; player1.delegate = self; player1.volume = 1.0; [player1 prepareToPlay]; [player1 play]; [sound release]; [url release]; } -(void)wrongSound { NSString *sound1 = [[NSString alloc] initWithFormat:@"boo"]; NSLog(@"sound boo %@", sound1); NSURL *url1 = [[NSURL alloc] initFileURLWithPath:[[NSBundle mainBundle] pathForResource:sound1 ofType:@"wav"]]; NSLog(@"boo url %@", url1); NSError *error; player2 = [[AVAudioPlayer alloc] initWithContentsOfURL:url1 error:&error]; NSLog(@"localizedDescription = %@",[error localizedDescription]); player2.delegate = self; player2.volume = 1.0; [player2 prepareToPlay]; [player2 play]; [sound1 release]; [url1 release]; } Update Play multiple audio files using AVAudioPlayer I have seen this link, but It is not helpful to me. How can this be done? Code samples will be greatly appreciated. In console- the following error description appeared. localizedDescription = The operation couldn’t be completed. (OSStatus error 1685348671.) Please help me to over come this problem. Thanks in Advance A: I corrected my self by converting the WAV format to MP3. Now its Playing correctly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517520", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Transfer a file from an Android to another Android via Wifi as it's done by Bluetooth? I'm making a schoolar proyect which envolves Android programming. I've already done most of the work but now I need to send one file or a buffered string line from an Android phone to another one via Wifi. I can't use the Bluetooth because it's already used and Wifi is pretty much faster. The phone that will send the data is 2.2 and I can use it as a host (or hope that it could work like that) and the receiver will be a 2.1. Any idea of what can I do or where can I get some info??? I think that I have to be more especific in my question. The data that I want to send is the "view" of the camera or the instant "videoview", like an Android Webcam. The Bluetooth is very bussy sending insctructions to a little robot and receiving the status also of the bot. So it would be insane to do it like rastur says as sms. And Graeme, I am not really interested in how secure it is (or am I wrong and start to worry about it) cause it will only be what the Android camera see and it is for a school project. Could you share me more info please???? Thanks. A: I dont think you have lots of choices here. You could send a SMS text message with attachment. Else you are talking about having one device post to some public bulleting board or website and have the other phone pick it up. Really bluetooth is the standard for what you want. A: The only way I can see this working is so: Have one phone set to "listen" to other phones on the network by opening a network connection to listen for UDP packets. Have the other phone set to "broadcast" by sending out these broadcast packets containing their IP. The listener should then be able to post data directly to that IP and the other should be able to receive it. (It should be possible for both phones to be listening and broadcasting via UDP as well as having an open listening TCP/IP connection to be ready for incoming data at the same time). Using UDP without encryption is very insecure. The technicalities in how you would do this is probably better asked in a separate question.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517523", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Understanding the Gemfile.lock file After running the bundle install command, 'Gemfile.lock' is created in the working directory. What do the directives inside that file mean? For example, let's take the following file: PATH remote: . specs: gem_one (0.0.1) GEM remote: http://example.org/ specs: gem_two (0.0.2) gem_three (0.0.3) gem_four (0.0.4) PLATFORMS platform DEPENDENCIES gem_two gem_one! What do 'PATH', 'GEM', 'PLATFORMS' and 'DEPENDENCIES' describe? Are all of them required? What should contain the 'remote' and 'specs' subdirectives? What does the exclamation mark after the gem name in the 'DEPENDENCIES' group mean? A: It looks to me like PATH lists the first-generation dependencies directly from your gemspec, whereas GEM lists second-generation dependencies (i.e. what your dependencies depend on) and those from your Gemfile. PATH::remote is . because it relied on a local gemspec in the current directory to find out what belongs in PATH::spec, whereas GEM::remote is rubygems.org, since that's where it had to go to find out what belongs in GEM::spec. In a Rails plugin, you'll see a PATH section, but not in a Rails app. Since the app doesn't have a gemspec file, there would be nothing to put in PATH. As for DEPENDENCIES, gembundler.com states: Runtime dependencies in your gemspec are treated like base dependencies, and development dependencies are added by default to the group, :development The Gemfile generated by rails plugin new my_plugin says something similar: # Bundler will treat runtime dependencies like base dependencies, and # development dependencies will be added by default to the :development group. What this means is that the difference between s.add_development_dependency "july" # (1) and s.add_dependency "july" # (2) is that (1) will only include "july" in Gemfile.lock (and therefore in the application) in a development environment. So when you run bundle install, you'll see "july" not only under PATH but also under DEPENDENCIES, but only in development. In production, it won't be there at all. However, when you use (2), you'll see "july" only in PATH, not in DEPENDENCIES, but it will show up when you bundle install from a production environment (i.e. in some other gem that includes yours as a dependency), not only development. These are just my observations and I can't fully explain why any of this is the way it is but I welcome further comments. A: You can find more about it in the bundler website (emphasis added below for your convenience): After developing your application for a while, check in the application together with the Gemfile and Gemfile.lock snapshot. Now, your repository has a record of the exact versions of all of the gems that you used the last time you know for sure that the application worked... This is important: the Gemfile.lock makes your application a single package of both your own code and the third-party code it ran the last time you know for sure that everything worked. Specifying exact versions of the third-party code you depend on in your Gemfile would not provide the same guarantee, because gems usually declare a range of versions for their dependencies. A: I've spent the last few months messing around with Gemfiles and Gemfile.locks a lot whilst building an automated dependency update tool1. The below is far from definitive, but it's a good starting point for understanding the Gemfile.lock format. You might also want to check out the source code for Bundler's lockfile parser. You'll find the following headings in a lockfile generated by Bundler 1.x: GEM (optional but very common) These are dependencies sourced from a Rubygems server. That may be the main Rubygems index, at Rubygems.org, or it may be a custom index, such as those available from Gemfury and others. Within this section you'll see: * *remote: one or more lines specifying the location of the Rubygems index(es) *specs: a list of dependencies, with their version number, and the constraints on any subdependencies GIT (optional) These are dependencies sourced from a given git remote. You'll see a different one of these sections for each git remote, and within each section you'll see: * *remote: the git remote. E.g., git@github.com:rails/rails *revision: the commit reference the Gemfile.lock is locked to *tag: (optional) the tag specified in the Gemfile *specs: the git dependency found at this remote, with its version number, and the constraints on any subdependencies PATH (optional) These are dependencies sourced from a given path, provided in the Gemfile. You'll see a different one of these sections for each path dependency, and within each section you'll see: * *remote: the path. E.g., plugins/vendored-dependency *specs: the git dependency found at this remote, with its version number, and the constraints on any subdependencies PLATFORMS The Ruby platform the Gemfile.lock was generated against. If any dependencies in the Gemfile specify a platform then they will only be included in the Gemfile.lock when the lockfile is generated on that platform (e.g., through an install). DEPENDENCIES A list of the dependencies which are specified in the Gemfile, along with the version constraint specified there. Dependencies specified with a source other than the main Rubygems index (e.g., git dependencies, path-based, dependencies) have a ! which means they are "pinned" to that source2 (although one must sometimes look in the Gemfile to determine in). RUBY VERSION (optional) The Ruby version specified in the Gemfile, when this Gemfile.lock was created. If a Ruby version is specified in a .ruby_version file instead this section will not be present (as Bundler will consider the Gemfile / Gemfile.lock agnostic to the installer's Ruby version). BUNDLED WITH (Bundler >= v1.10.x) The version of Bundler used to create the Gemfile.lock. Used to remind installers to update their version of Bundler, if it is older than the version that created the file. PLUGIN SOURCE (optional and very rare) In theory, a Gemfile can specify Bundler plugins, as well as gems3, which would then be listed here. In practice, I'm not aware of any available plugins, as of July 2017. This part of Bundler is still under active development! * *https://dependabot.com *https://github.com/bundler/bundler/issues/4631 *http://andre.arko.net/2012/07/23/towards-a-bundler-plugin-system/ A: in regards to the exclamation mark I just found out it's on gems fetched via :git, e.g. gem "foo", :git => "git@github.com:company/foo.git" A: It seems no clear document talking on the Gemfile.lock format. Maybe it's because Gemfile.lock is just used by bundle internally. However, since Gemfile.lock is a snapshot of Gemfile, which means all its information should come from Gemfile (or from default value if not specified in Gemfile). For GEM, it lists all the dependencies you introduce directly or indirectly in the Gemfile. remote under GEM tells where to get the gems, which is specified by source in Gemfile. If a gem is not fetch from remote, PATH tells the location to find it. PATH's info comes from path in Gemfile when you declare a dependency. And PLATFORM is from here. For DEPENDENCIES, it's the snapshot of dependencies resolved by bundle. A: Bundler is a Gem manager which provides a consistent environment for Ruby projects by tracking and installing the exact gems and versions that are needed. Gemfile and Gemfile.lock are primary products given by Bundler gem (Bundler itself is a gem). Gemfile contains your project dependency on gem(s), that you manually mention with version(s) specified, but those gem(s) inturn depends on other gem(s) which is resolved by bundler automatically. Gemfile.lock contain complete snapshot of all the gem(s) in Gemfile along with there associated dependency. When you first call bundle install, it will create this Gemfile.lock and uses this file in all subsequent calls to bundle install, which ensures that you have all the dependencies installed and will skip dependency installation. Same happens when you share your code with different machines You share your Gemfile.lock along with Gemfile, when you run bundle install on other machine it will refer to your Gemfile.lock and skip dependency resolution step, instead it will install all of the same dependent gem(s) that you used on the original machine, which maintains consistency across multiple machines Why do we need to maintain consistency along multiple machines ? * *Running different versions on different machines could lead to broken code *Suppose, your app used the version 1.5.3 and it works 14 months ago without any problems, and you try to install on different machine without Gemfile.lock now you get the version 1.5.8. Maybe it's broken with the latest version of some gem(s) and your application will fail. Maintaining consistency is of utmost importance (preferred practice). It is also possible to update gem(s) in Gemfile.lock by using bundle update. This is based on the concept of conservative updating A: What does the exclamation mark after the gem name in the 'DEPENDECIES' group mean? The exclamation mark appears when the gem was installed using a source other than "https://rubygems.org".
{ "language": "en", "url": "https://stackoverflow.com/questions/7517524", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "209" }
Q: Adding A Custom Discount Order Total in Magento Does Not Change Sales Tax I have created a custom order total that gives a discount in certain situations. The grand total always comes out correct, however the sales tax calculation is not taking my discount into account when calculating (so if I was giving a discount of $10, the sales tax amount was calculated on the entire amount before my discount). Take for example the following: Subtotal: $856.49 Multi Unit Discounts: -$22.50 Shipping: $10.96 Tax: $52.05 Grand Total: $897.00 My custom discount is the Multi Unit Discounts. The tax rate is 6%. As you can see the grand total is correct based on all the line items, but the tax amount itself is not correct (it is based on all the line items except my discount). In my config.xml file I have the following to get my order total working in the system: <sales> <quote> <totals> <mud> <class>Wpe_Multiunitdiscount_Model_Multiunitdiscount</class> <before>tax</before> </mud> </totals> </quote> </sales> The following is the contents of my order total class: class Wpe_Multiunitdiscount_Model_Multiunitdiscount extends Mage_Sales_Model_Quote_Address_Total_Abstract { public function collect(Mage_Sales_Model_Quote_Address $address) { if ($address->getData('address_type')=='billing') return $this; $items = $address->getAllItems(); $total_discount = 0; foreach($items as $item) { $product_discounts = Mage::helper("multiunitdiscount")->findDiscounts($item); if($product_discounts > 0) { $total_discount += $product_discounts; } } $address->setMudAmount($total_discount); $address->setGrandTotal($address->getGrandTotal() - $address->getMudAmount() ); $address->setBaseGrandTotal($address->getBaseGrandTotal() - $address->getMudAmount()); return $this; } public function fetch(Mage_Sales_Model_Quote_Address $address) { if ($address->getData('address_type')=='billing') return $this; if($address->getMudAmount() > 0) { $address->addTotal(array( 'code' => $this->getCode(), 'title' => Mage::helper('sales')->__('Multi Unit Discounts'), 'value' => -$address->getMudAmount(), )); } return $this; } } For the sake of not posting a huge chunk of code in here that I am not sure is necessary, I can tell you that the helper in the above code simply returns the amount of money the discount is for that particular item in the quote. Can someone help point me in the right direction for getting the sales tax calculation correct? EDIT: In order to keep this simple, I have removed a lot of my logic behind calculating the discount and am now trying to simple take $10 off the order total as a discount. As suggested I did not modify the Grand Total of the address and am now only setting the Discount Amount and Base Discount Amount. Now the sales tax does not add up and the grand total is off. Maybe if there is a good tutorial out there that someone can point me towards would help? I do not seem to be grasping how the order totals all interact with each other. public function collect(Mage_Sales_Model_Quote_Address $address) { if ($address->getData('address_type')=='billing') return $this; $address->setMudDiscount(10); $address->setDiscountAmount($address->getDiscountAmount() + $address->getMudDiscount()); $address->setBaseDiscountAmount($address->getBaseDiscountAmount() + $address->getMudDiscount()); return $this; } public function fetch(Mage_Sales_Model_Quote_Address $address) { if ($address->getData('address_type')=='billing') return $this; $address->addTotal(array( 'code' => $this->getCode(), 'title' => Mage::helper('sales')->__('Multi Unit Discounts'), 'value' => -$address->getMudDiscount(), )); return $this; } A: Go to System > Configuration. Select "Tax" from the left hand navigation, then open the "Calculation Settings" group if it isn't already. Try changing the "Apply Customer Tax" parameter to "After Discount"
{ "language": "en", "url": "https://stackoverflow.com/questions/7517534", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: How to convert DWORDLONG to a char *? res = pRecord->Usn ; char sres[1024]; strcpy(sres,""); ltoa(res,sres, 10); I have this variable res, which is of type DWORDLONG, and I am trying to convert it into a string so that I can insert it into the database. Also, how would I convert it back. Is there a equivalent of ltoa, or do you have to write the logic yourself? A: Use boost::lexical_cast<std::string>(res); or std::ostringstream o; o << res; o.str(); or in C++11 std::to_string(res); For going back in C++11 you would use res=std::stoull(str) or in C *shiver * char* end; res=strtoull(str.c_str(),&end,10);
{ "language": "en", "url": "https://stackoverflow.com/questions/7517538", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: .NET 4 new TCP client fails to connect: No connection could be made because the target machine actively refused it I am having a simple issue with .NET 4 Sockets (TcpClient) in both win7 and xp. I get the error: No connection could be made because the target machine actively refused it This does not appear to be a firewall issue, since both the client and the server programs are on the same computer, and I don't have any local firewall enabled. I wrote both the server and client (they are talking on port 80 (I have also tried other ports such as 31000). Nothing else is running on port 80 on my machine. The client code is: public void makeConnection() { string server = ClientStatus.myself.ServerName; port = 80; ClientStatus.myself.BytesSent = 0.ToString(); client = new TcpClient(server, port); ClientStatus.myself.Connected = "connected"; stream = client.GetStream(); bytes = new Byte[1024]; } and I confired that the server and port are what I expect. The error occurs on new TcpClient(server, port), and it spins for about 4 seconds before the error occurs. I have also tried using an IP address (127.0.0.1) instead of "myhostname.domain.com" as the server (the alternate way to create a client socket) and it also fails. Here is the code for the server that I wrote: namespace SocketListener { class DataListener { public static DataListener myself; TcpListener server = null; Byte[] bytes; Int32 port; IPAddress localAddr; MainWindow w; public DataListener(MainWindow caller) { DataListener.myself = this; w = caller; Status.myself.Connected = "starting"; port = 80; localAddr = IPAddress.Parse("127.0.0.1"); server = new TcpListener(localAddr, port); bytes = new Byte[1024]; server.Start(); } public void acceptLoop() { TcpClient client; while (true) { // Perform a blocking call to accept requests. Status.myself.Connected = "waiting"; if (server.Pending()) { client = server.AcceptTcpClient(); Status.myself.Connected = "true"; Status.myself.BytesReceived = 0.ToString(); NetworkStream stream = client.GetStream(); dataLoop(stream); client.Close(); } else { Thread.Sleep(100); return; } // Shutdown and end connection Status.myself.Connected = "false"; } } public void dataLoop(NetworkStream stream) { int count = 0; int i; Status.myself.ByteRate = "0.0"; Stopwatch watch = new Stopwatch(); watch.Start(); while ((i = stream.Read(bytes, 0, bytes.Length)) != 0) { count += i; Status.myself.BytesReceived = count.ToString(); } watch.Stop(); double rate = count / (watch.ElapsedMilliseconds / 1000); rate = rate / (1024 * 1024); Status.myself.ByteRate = rate.ToString(); } public void shutdown() { server.Stop(); } } } A: I have win7 box. So accepting incomming connections is blocked (even local). The answer is: run netsh http add urlacl url=http://+:80/MyUri user=DOMAIN\user see: netsh http add urlacl : add reservation for a group
{ "language": "en", "url": "https://stackoverflow.com/questions/7517543", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I prevent Hibernate from updating NULL values Is there a setting in hibernate to ignore null values of properties when saving a hibernate object? NOTE In my case I am de-serializing JSON to a Hibernate Pojo via Jackson. The JSON only contains some of the fields of the Pojo. If I save the Pojo the fields that were not in the JSON are null in the Pojo and hibernate UPDATES them. I came accross the setting updateable=false, but this isn't a 100% solution. http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#entity-mapping-property Maybe somebody has another idea... NOTE 2: According to the Hibernate Docs the dynamicUpdate annotation does exactly that dynamicInsert / dynamicUpdate (defaults to false): specifies that INSERT / UPDATE SQL should be generated at runtime and contain only the columns whose values are not null. http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#mapping-declaration-class Funny enough if you define it in XML via dynamic-update the docu do not mention the hanlding of NULL values. dynamic-update (optional - defaults to false): specifies that UPDATE SQL should be > generated at runtime and can contain only those columns whose values have changed. Due to the fact that I'm using both annotations AND xml configuration, hibernate seems to ignores my dynamicUpdate=true annotation. A: You should first load the object using the primary key from DB and then copy or deserialize the JSON on top of it. There is no way for hibernate to figure out whether a property with value null has been explicitly set to that value or it was excluded. If it is an insert then dynamic-insert=true should work. A: I have googled a lot about this,but there is no the very solution for me.So,I used a not graceful solution to cover it. public void setAccount(Account a) throws HibernateException { try { Account tmp = (Account) session. get(Account.class, a.getAccountId()); tmp.setEmail(getNotNull(a.getEmail(), tmp.getEmail())); ... tmp.setVersion(getNotNull(a.getVersion(), tmp.getVersion())); session.beginTransaction(); session.update(tmp); session.getTransaction().commit(); } catch (HibernateException e) { logger.error(e.toString()); throw e; } } public static <T> T getNotNull(T a, T b) { return b != null && a != null && !a.equals(b) ? a : b; } I receive an Object a which contains a lot of fields.Those field maybe null,but I don't want to update them into mysql. I get an tmp Obejct from db, and change the field by method getNotNull,then update the Object. a Chinese description edition A: I bumped into this problem and I did a work-around to help myself through this. May be a little ugly but may work just fine for you too. Kindly if someone feels there's an adjustment that's good to have feel free to add. Note that the work-around is meant for valid entity classes and whose some fields include nullable attributes. Advantage with this one is it reduces the number of queries. public String getUpdateJPQL(Object obj, String column, Object value) throws JsonProcessingException, IOException { //obj -> your entity class object //column -> field name in the query clause //value -> value of the field in the query clause ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(obj); Map<String, Object> map = mapper.readValue(json, Map.class); Map format = new HashMap(); if (value instanceof String) { value = "'" + value + "'"; } map.keySet() .forEach((str) -> { Object val = map.get(str); if (val != null) { format.put("t.".concat(str), "'" + val + "'"); } }); String formatStr = format.toString(); formatStr = formatStr.substring(1, formatStr.length() - 1); return "update " + obj.getClass() .getSimpleName() + " t set " + formatStr + " where " + column + " = " + value + ""; } Example: For entity type User with fields: userId, userName & userAge; the result query of getUpdateJPQL(user, userId, 2) should be update User t set t.userName = 'value1', t.userAge = 'value2' where t.userId = 2 Note that you can use json annotations like @JsonIgnore on userId field to exclude it in deserialization i.e. in the generated query. You can then run your query using entityManager or hibernate sessions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517546", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: css: capitalizing hard-coded uppercase text I have content that is in uppercase ( that's the way it's persisted on the back end ) and I have to transform it into 'proper case'. I'm finding out that 'text-transform:capitalize' doesn't work. I suspect there's no css based workaround for that either. .text-test{ text-transform:capitalize; } ... <h1 class="text-test">SOME UPPER CASE TEXT</h1> Is my conclusion correct? Thanks A: CSS does not support sentence case conversion. Fix it in the server or you're going to have to use JavaScript to re-write the HTML. See: How to give sentence case to sentences through CSS or javascript? A: Capitalise won't work as it targets on the first letter of whatever you're targeting so the rest of the text won't be affected. You'll have to edit it in the HTML or maybe a jQuery solution can be found, I care :) A: Title Case String.prototype.toTitleCase = function() { return this.replace(/\w\S*/g, function(t) { return t.charAt(0).toUpperCase() + t.substr(1).toLowerCase();}); }; var s1 = "HELLO WORLD!"; alert(s1.toTitleCase()); output Hello World! This isn't as elegant as a solution that would say convert it to Hello world! However I'm sure you can use this as a start point. A: Somewhat very (very) late, but can help others. What about: .text-test {text-transform: lowercase;} .text-test::first-letter {text-transform:capitalize;}
{ "language": "en", "url": "https://stackoverflow.com/questions/7517554", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: MFMailComposeViewController Not Working in Landscape My app uses landscape mode. When trying to integrate MFMailComposeViewController that always worked for me in my other portrait mode apps, I came across the issue of mail controller not showing up at all. I found a lot of info during research and I tried to overwrite MFMailComposeViewController like it suggests here: mfmailcomposeviewcontroller in landscape However, it still acts the same way. In short, my View-based app has a main controller A and other controllers B and C, for example. B is open on top of A and it has the MFMailComposeViewController which, when running, hides B and goes back to A. This is very strange but I feel like it has to do with view hierarchy and where exactly I need to add MFMailComposeViewController. When overwritten (as in a link above), this code does not resolve my problem: MailCompose *controller = [[MailCompose alloc] init]; controller.mailComposeDelegate = self; I appreciate any additional suggestions. Here is the code I am using: if ([MFMailComposeViewController canSendMail]){ MailCompose *picker = [[MailCompose alloc]init]; //MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];//was before I subclassed picker.mailComposeDelegate = self; [picker setToRecipients:[NSArray arrayWithObject:@"info@site.com"]]; [picker setSubject:@"Feedback"]; [picker setMessageBody:emailBody isHTML:YES]; picker.navigationBar.barStyle = UIBarStyleBlack; [self presentModalViewController:picker animated:YES]; [picker release]; } A: The code you have for calling the composer looks spot on, but you already know that. So it can only be something like: * *the code is never called *the device isn't sending mail (these two can be checked with the debugger) * *you are presenting this view from the wrong place, eg from a view that is already presenting a modal view controller (didn't know if this was possible?) *you have added a new window to the app at alert or status bar level, this will obscure the composer when it is presented. Bit of a set of guesses, I hope one of them works for you!
{ "language": "en", "url": "https://stackoverflow.com/questions/7517562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Receiving voip calls while application is in background in ios I think i have all the requirements to have an "alive" socket while the app is in background. That is to say: * *My application has voip and audio as its background modes. *I'm using PJSIP as the SIP library, which is supposed to use CFReadStreams with the "Run in Background" property enabled *The app is using TCP to establish the connection with the SIP server. When the application is sent to background, it adds a background handler which sends a "keepAlive" message each period of time. That keepAlive seems to be working. If I check the logs in the server I can see how messages arrive even when the application is not in foreground. The problem ( and the question ) is, I'm not receiving calls while the application is in background. It seems that the socket is still alive, if I make a call to the cell phone while the app is no in the foreground, nothing happens, but if I launch the app by myself, the call is automatically detected. Thanks :) A: We found the problem. Given the current configuration, the Server used a different connection to send the INVITE request from the initial TCP socket used from the phone to send the intial REGISTER request. As the two sockets were different, the Operating System didn't wake the application. If you configure the server (Kamailio in our case) to reuse the initial socket which the phone used to send the first REGISTER it works seamlessly. By default, it seems that the SIP servers create new sockets for each INVITE request they want to send to the phone. This situation IS a problem to iphone background model. A: Just to double-check, you've read this: http://trac.pjsip.org/repos/wiki/Getting-Started/iPhone#UnabletoacceptincomingcallinbackgroundmodeiOS4 Also, try it with the latest 1.x branch from Subversion repository, there have been several fixes to iOS support.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517563", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: mootools Sortable detach I'm working on an interface using Mootools 1.3 that will have two columns of information-- on the left, "available elements" and on the right "selected elements". You'll pull from the list of avail. in the left, and pull to the right, where you will be able to sort. Here's a fiddle: http://jsfiddle.net/Um3xK/1/ What I'd like is to detach the "sort" from the left column, since it's not needed and could be confusing, but leave the sort on the right-- and possibly detach the "drag left" from the right column, since you won't need to pull items from right to left, only from left to right. Is this possible? From reading the Mootools docs it seems like if you use the "detach" method it'll detach all click/drag events. A: One workaround is: * *make one of the lists (for example, the right one) sortable; *use Drag.Move to coordinate the drag and drop; *When an item from the left is dropped into the right list, using addItem of Sortables.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517565", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Difference between two strings C# Lets say I have two strings: string s1 = "hello"; string s2 = "hello world"; Is there a way I can get a string s3 = " world"; which is the difference between the 2 strings? EDIT: The difference will be always in this scenario s1 = "abc" s2 = "abcd ads as " A: string s1 = "hello"; string s2 = "hello world"; string s3 = s2.replace(s1,""); A: With a simple replace string s3 = s2.Replace(s1, ""); A: If the case you define is correct an alternative solution would be: string s3 = s2.substring(s1.Length); This is presuming that the second string begins with exactly the same characters as the first string and you merely want to chop off the initial duplication. A: Use string s3 = s2.Replace(s1, ""); EDIT: Note that all occurrences of s1 in s2 will be absent from s3. Make sure to carefully consider the comments on this post to confirm this is your desired result, for example the scenarios mentioned in @mellamokb's comment. A: IF (big "if") s1 is always a substring of s2, then you could work with .IndexOf and .Length to find where in s2 that s1 is. A: First answer without conditions outside of the code: string s3 = null; if (s2.StartsWith(s1)) { s3 = s2.Substring(s1.Length); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7517571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: Playing video with many particles animated on top I am playing a movie using an AVPlayer and animating 500 falling particles on top. I tried to simply add 500 animated CALAyers. I tried several variations on that but performance is always a problem. As soon as I get more then around 100 CALayers, the video gets choppy. What would be the proper way to do this? I thought maybe this should be done using OpenGL, but I never used it and can't find how to have a video played in OpenGL. I can get the background videos as separate frame pngs, but being fullscreen, the content size gets quite big quite fast. A: Try drawing the particles into a much smaller number of CALayers, multiple particles per layer bitmap, one for each speed of falling, etc. Then redraw the layers in background threads as needed so as not to impact the composited on video frame rate. A: Take a look at this post Alternatives to creating an openGL texture from a captured video frame to overlay an openGL view over video? (iPhone). Brad shows how to render video to OpenGL textures. You can then render your particles over a video textured plane. For interaction, you could integrate a physics engine such as Bullet to exert forces to areas of the screen to interact with the particles. If you can wait, I think this will get much easier (video to texture stream) in iOS5. A: We ended up running an OpenGL layer using Cocos2D over our video animation. The performance was impacted a little but for our need, it was alright.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517575", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Powershell format-table error I am attempting to run the following code to retrieve a list of local users on a machine. gwmi win32_useraccount -Computername $env:computername -Filter "Domain='$env:computername'" | Format-Table Name,Description I get this error when running inside a PS1 file: The object of type "Microsoft.PowerShell.Commands.Internal.Format.FormatStartData" is not valid or not in the correct sequence. This is likely caused by a user-specified "f ormat-table" command which is conflicting with the default formatting. + CategoryInfo : InvalidData: (:) [out-lineoutput], InvalidOperationException + FullyQualifiedErrorId : ConsoleLineOutputOutOfSequencePacket,Microsoft.PowerShell.Commands.OutLineOutputCommand I understand this issue arises because of the way the pipelines are parsed but I can't figure out how to get around it. A: The Format-* cmdlets do not do final output, but transform their input into a sequence of formatting objects. These formatting objects are converted to the actual output by one of the Out- cmdlets, probably Out-Default. If a script has multiple, different, sets of formatting objects that final output of the merged objects from all the expressions in the script Out-Default cannot resolve the inconsistencies. Fix: add a Out-Sting to the end of each output generating pipeline to perform the formatting one expression at a time: gwmi win32_useraccount -Computername $env:computername -Filter "Domain='$env:computername'" | Format-Table Name,Description | Out-String A: you can also try : gwmi win32_useraccount -Computername $env:computername -Filter "Domain='$env:computername'" | Select-Object Name,Description | Format-Table Name,Description In fact you convert to an intermediate PSCustomObject and you still have an object.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517581", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: HTML5 canvas issue? Here is my JS code: function Show(output, startX, startY){ var c = document.getElementById("myCanvas"); var context = c.getContext("2d"); context.fillText ("A" , startX, startY); context.font = 'bold 20px sans-serif'; context.fillText ("B" , startX, startY + 50); } Show(outputcpu, 50, 50); Show(outputio, 150, 50); what I expect is some thing like: A A B B But I'm not sure why what i get is: A A B B I think the issue due to context.font last until the next function call. But I don't know how to stop it! Any idea!? A: You'll need to reset the font before you draw - try: function Show(output, startX, startY){ var c = document.getElementById("myCanvas"); var context = c.getContext("2d"); context.font = ' 20px sans-serif'; context.fillText ("A" , startX, startY); context.font = 'bold 20px sans-serif'; context.fillText ("B" , startX, startY + 50); } Show(outputcpu, 50, 50); Show(outputio, 150, 50); Here is a fiddle - http://jsfiddle.net/8Tuzp/ EDIT: If you really don't like changing the font twice (I see no problem with doing so), you can save the canvas state and restore it once you have draw the bold text. Restoring the canvas context back to before you changed the font. function Show(output, startX, startY){ var c = document.getElementById("myCanvas"); var context = c.getContext("2d"); context.save(); context.fillText ("A" , startX, startY); context.font = 'bold 20px sans-serif'; context.fillText ("B" , startX, startY + 50); context.restore(); } Show(null, 50, 50); Show(null, 150, 50); A: You need to set the font weight back to normal as context properties are persistent across getContext() calls: context.fillText ("A" , startX, startY); context.font = 'bold 20px sans-serif'; context.fillText ("B" , startX, startY + 50); context.font = '20px sans-serif';
{ "language": "en", "url": "https://stackoverflow.com/questions/7517582", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to install JpGraph Can some one please let me know how to install and configure (JpGraph.http://jpgraph.net/doc/faq.php) I saw the articles of that site but I cannot understand that.. Please help me..Thank you in advance A: Did you try out any examples. You can download jpgraph files here The basic bar graph example is here
{ "language": "en", "url": "https://stackoverflow.com/questions/7517583", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Different floating point result with optimization enabled - compiler bug? The below code works on Visual Studio 2008 with and without optimization. But it only works on g++ without optimization (O0). #include <cstdlib> #include <iostream> #include <cmath> double round(double v, double digit) { double pow = std::pow(10.0, digit); double t = v * pow; //std::cout << "t:" << t << std::endl; double r = std::floor(t + 0.5); //std::cout << "r:" << r << std::endl; return r / pow; } int main(int argc, char *argv[]) { std::cout << round(4.45, 1) << std::endl; std::cout << round(4.55, 1) << std::endl; } The output should be: 4.5 4.6 But g++ with optimization (O1 - O3) will output: 4.5 4.5 If I add the volatile keyword before t, it works, so might there be some kind of optimization bug? Test on g++ 4.1.2, and 4.4.4. Here is the result on ideone: http://ideone.com/Rz937 And the option I test on g++ is simple: g++ -O2 round.cpp The more interesting result, even I turn on /fp:fast option on Visual Studio 2008, the result still is correct. Further question: I was wondering, should I always turn on the -ffloat-store option? Because the g++ version I tested is shipped with CentOS/Red Hat Linux 5 and CentOS/Redhat 6. I compiled many of my programs under these platforms, and I am worried it will cause unexpected bugs inside my programs. It seems a little difficult to investigate all my C++ code and used libraries whether they have such problems. Any suggestion? Is anyone interested in why even /fp:fast turned on, Visual Studio 2008 still works? It seems like Visual Studio 2008 is more reliable at this problem than g++? A: Intel x86 processors use 80-bit extended precision internally, whereas double is normally 64-bit wide. Different optimization levels affect how often floating point values from CPU get saved into memory and thus rounded from 80-bit precision to 64-bit precision. Use the -ffloat-store gcc option to get the same floating point results with different optimization levels. Alternatively, use the long double type, which is normally 80-bit wide on gcc to avoid rounding from 80-bit to 64-bit precision. man gcc says it all: -ffloat-store Do not store floating point variables in registers, and inhibit other options that might change whether a floating point value is taken from a register or memory. This option prevents undesirable excess precision on machines such as the 68000 where the floating registers (of the 68881) keep more precision than a "double" is supposed to have. Similarly for the x86 architecture. For most programs, the excess precision does only good, but a few programs rely on the precise definition of IEEE floating point. Use -ffloat-store for such programs, after modifying them to store all pertinent intermediate computations into variables. In x86_64 builds compilers use SSE registers for float and double by default, so that no extended precision is used and this issue doesn't occur. gcc compiler option -mfpmath controls that. A: Different compilers have different optimization settings. Some of those faster optimization settings do not maintain strict floating-point rules according to IEEE 754. Visual Studio has a specific setting, /fp:strict, /fp:precise, /fp:fast, where /fp:fast violates the standard on what can be done. You might find that this flag is what controls the optimization in such settings. You may also find a similar setting in GCC which changes the behaviour. If this is the case then the only thing that's different between the compilers is that GCC would look for the fastest floating point behaviour by default on higher optimisations, whereas Visual Studio does not change the floating point behaviour with higher optimization levels. Thus it might not necessarily be an actual bug, but intended behaviour of an option you didn't know you were turning on. A: To those who can't reproduce the bug: do not uncomment the commented out debug stmts, they affect the result. This implies that the problem is related to the debug statements. And it looks like there's a rounding error caused by loading the values into registers during the output statements, which is why others found that you can fix this with -ffloat-store Further question: I was wondering, should I always turn on -ffloat-store option? To be flippant, there must be a reason that some programmers don't turn on -ffloat-store, otherwise the option wouldn't exist (likewise, there must be a reason that some programmers do turn on -ffloat-store). I wouldn't recommend always turning it on or always turning it off. Turning it on prevents some optimizations, but turning it off allows for the kind of behavior you're getting. But, generally, there is some mismatch between binary floating point numbers (like the computer uses) and decimal floating point numbers (that people are familiar with), and that mismatch can cause similar behavior to what your getting (to be clear, the behavior you're getting is not caused by this mismatch, but similar behavior can be). The thing is, since you already have some vagueness when dealing with floating point, I can't say that -ffloat-store makes it any better or any worse. Instead, you may want to look into other solutions to the problem you're trying to solve (unfortunately, Koenig doesn't point to the actual paper, and I can't really find an obvious "canonical" place for it, so I'll have to send you to Google). If you're not rounding for output purposes, I would probably look at std::modf() (in cmath) and std::numeric_limits<double>::epsilon() (in limits). Thinking over the original round() function, I believe it would be cleaner to replace the call to std::floor(d + .5) with a call to this function: // this still has the same problems as the original rounding function int round_up(double d) { // return value will be coerced to int, and truncated as expected // you can then assign the int to a double, if desired return d + 0.5; } I think that suggests the following improvement: // this won't work for negative d ... // this may still round some numbers up when they should be rounded down int round_up(double d) { double floor; d = std::modf(d, &floor); return floor + (d + .5 + std::numeric_limits<double>::epsilon()); } A simple note: std::numeric_limits<T>::epsilon() is defined as "the smallest number added to 1 that creates a number not equal to 1." You usually need to use a relative epsilon (i.e., scale epsilon somehow to account for the fact that you're working with numbers other than "1"). The sum of d, .5 and std::numeric_limits<double>::epsilon() should be near 1, so grouping that addition means that std::numeric_limits<double>::epsilon() will be about the right size for what we're doing. If anything, std::numeric_limits<double>::epsilon() will be too large (when the sum of all three is less than one) and may cause us to round some numbers up when we shouldn't. Nowadays, you should consider std::nearbyint(). A: The accepted answer is correct if you are compiling to an x86 target that doesn't include SSE2. All modern x86 processors support SSE2, so if you can take advantage of it, you should: -mfpmath=sse -msse2 -ffp-contract=off Let's break this down. -mfpmath=sse -msse2. This performs rounding by using SSE2 registers, which is much faster than storing every intermediate result to memory. Note that this is already the default on GCC for x86-64. From the GCC wiki: On more modern x86 processors that support SSE2, specifying the compiler options -mfpmath=sse -msse2 ensures all float and double operations are performed in SSE registers and correctly rounded. These options do not affect the ABI and should therefore be used whenever possible for predictable numerical results. -ffp-contract=off. Controlling rounding isn't enough for an exact match, however. FMA (fused multiply-add) instructions can change the rounding behavior versus its non-fused counterparts, so we need to disable it. This is the default on Clang, not GCC. As explained by this answer: An FMA has only one rounding (it effectively keeps infinite precision for the internal temporary multiply result), while an ADD + MUL has two. By disabling FMA, we get results that exactly match on debug and release, at the cost of some performance (and accuracy). We can still take advantage of other performance benefits of SSE and AVX. A: Output should be: 4.5 4.6 That's what the output would be if you had infinite precision, or if you were working with a device that used a decimal-based rather than binary-based floating point representation. But, you aren't. Most computers use the binary IEEE floating point standard. As Maxim Yegorushkin already noted in his answer, part of the problem is that internally your computer is using an 80 bit floating point representation. This is just part of the problem, though. The basis of the problem is that any number of the form n.nn5 does not have an exact binary floating representation. Those corner cases are always inexact numbers. If you really want your rounding to be able to reliably round these corner cases, you need a rounding algorithm that addresses the fact that n.n5, n.nn5, or n.nnn5, etc. (but not n.5) is always inexact. Find the corner case that determines whether some input value rounds up or down and return the rounded-up or rounded-down value based on a comparison to this corner case. And you do need to take care that a optimizing compiler will not put that found corner case in an extended precision register. See How does Excel successfully Rounds Floating numbers even though they are imprecise? for such an algorithm. Or you can just live with the fact that the corner cases will sometimes round erroneously. A: I digged more into this problem and I can bring more precisions. First, the exact representations of 4.45 and 4.55 according to gcc on x84_64 are the following (with libquadmath to print the last precision): float 32: 4.44999980926513671875 double 64: 4.45000000000000017763568394002504646778106689453125 doublex 80: 4.449999999999999999826527652402319290558807551860809326171875 quad 128: 4.45000000000000000000000000000000015407439555097886824447823540679418548304813185723105561919510364532470703125 float 32: 4.55000019073486328125 double 64: 4.54999999999999982236431605997495353221893310546875 doublex 80: 4.550000000000000000173472347597680709441192448139190673828125 quad 128: 4.54999999999999999999999999999999984592560444902113175552176459320581451695186814276894438080489635467529296875 As Maxim said above, the problem is due to the 80 bits size of the FPU registers. But why is the problem never occuring on Windows? on IA-32, the x87 FPU was configured to use an internal precision for the mantissa of 53 bits (equivalent to a total size of 64 bits: double). For Linux and Mac OS, the default precision of 64 bits was used (equivalent to a total size of 80 bits: long double). So the problem should be possible, or not, on these different platforms by changing the control word of the FPU (assuming the sequence of instructions would trigger the bug). The issue was reported to gcc as bug 323 (read at least the comment 92! ). To show the mantissa precision on Windows, you can compile this in 32 bits with VC++: #include "stdafx.h" #include <stdio.h> #include <float.h> int main(void) { char t[] = { 64, 53, 24, -1 }; unsigned int cw = _control87(0, 0); printf("mantissa is %d bits\n", t[(cw >> 16) & 3]); } and on Linux/Cygwin: #include <stdio.h> int main(int argc, char **argv) { char t[] = { 24, -1, 53, 64 }; unsigned int cw = 0; __asm__ __volatile__ ("fnstcw %0" : "=m" (*&cw)); printf("mantissa is %d bits\n", t[(cw >> 8) & 3]); } Note that with gcc you can set the FPU precision with -mpc32/64/80, though it is ignored in Cygwin. But keep in mind that it will modify the size of the mantissa, but not the exponent one, letting the door open to other kinds of different behavior. On x86_64 architecture, SSE is used as said by tmandry, so the problem will not occur unless you force the old x87 FPU for FP computing with -mfpmath=387, or unless you compile in 32 bits mode with -m32 (you will need multilib package). I could reproduce the problem on Linux with different combinations of flags and versions of gcc: g++-5 -m32 floating.cpp -O1 g++-8 -mfpmath=387 floating.cpp -O1 I tried a few combinations on Windows or Cygwin with VC++/gcc/tcc but the bug never showed up. I suppose the sequence of instruction generated is not the same. Finally, note that an exotic way to prevent this problem with 4.45 or 4.55 would be to use _Decimal32/64/128, but support is really scarce... I spent a lot of time just to be able to do a printf with libdfp ! A: Personally, I have hit the same problem going the other way - from gcc to VS. In most instances I think it is better to avoid optimisation. The only time it is worthwhile is when you're dealing with numerical methods involving large arrays of floating point data. Even after disassembling I'm often underwhelmed by the compilers choices. Very often it's just easier to use compiler intrinsics or just write the assembly yourself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517588", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "120" }
Q: cant fill array java hi ive got a public array of ints and i want to store 1 or 2 in the array but im getting the error NullPointerException what im doing is this public int[] which; public int gotIt; public void Check() { int cont = 0; System.out.println(intento[0]); for(int j = 0;j <= spaces;++j) { if(tries[0] == words[numRandom][j]) { which[gotIt] = j;//im getting the error here gotIt++; } else { cont++; } } if(Contador == espacios+1) { Errors++; System.out.println("There was an error"); } repaint(); } the error is when im filling the variable called which i have no idea why is that,thank you very much A: You need to allocate the array before you can access its elements: public int[] which = new int[n]; where n is the desired size of the array. If you don't know the size of the array upfront, you can leave the variable declaration as-is, and do the allocation later on (but before you attempt to use the array): which = new int[n];
{ "language": "en", "url": "https://stackoverflow.com/questions/7517594", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Sorting issue iphone sdk Having some problem, I got it sorted but looks likes this, "10/16/2011 12:00:00 AM", "10/16/2011 12:00:00 AM", "11/16/2011 12:00:00 AM", "11/16/2011 12:00:00 AM", "9/15/2011 12:00:00 AM", "9/15/2011 12:00:00 AM", "9/15/2011 12:00:00 AM" the format is "MM/dd/yyyy", I want to sort this based on day, then month, then year then time. How can I implement that? Here is the code NSSortDescriptor* nameSorter = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES]; NSMutableArray *temp = [dateStart mutableCopy]; [temp sortUsingDescriptors:[NSArray arrayWithObject:nameSorter]]; dateStart = temp; NSLog(@"Sorted: %@",dateStart); A: You can use NSDateFormatter to convert the string into NSDate and Comparator to compare them, NSArray *datesArray = @[@"10/16/2011 12:00:00 AM", @"10/16/2011 12:00:00 AM", @"11/16/2011 12:00:00 AM", @"11/16/2011 12:00:00 AM", @"9/15/2011 12:00:00 AM", @"9/15/2011 12:00:00 AM", @"9/15/2011 12:00:00 AM"]; NSLog(@"dates:%@", datesArray); NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"MM/dd/yyyy h:mm:ss a"]; NSArray *sortedDatesArray = [datesArray sortedArrayUsingComparator:^(id obj1, id obj2){ NSDate *date1 = [dateFormatter dateFromString:obj1]; NSDate *date2 = [dateFormatter dateFromString:obj2]; return [date1 compare:date2]; }]; NSLog(@"%@",sortedDatesArray); Output: "9/15/2011 12:00:00 AM", "9/15/2011 12:00:00 AM", "9/15/2011 12:00:00 AM", "10/16/2011 12:00:00 AM", "10/16/2011 12:00:00 AM", "11/16/2011 12:00:00 AM", "11/16/2011 12:00:00 AM"
{ "language": "en", "url": "https://stackoverflow.com/questions/7517595", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UITextView didEndEditing isn't called on iPad The method textViewDidEndEditing is not called when you dismiss the keyboard on the iPad with the button in the right corner at the button. However, i want the method to be called so that I basically can access the written text. Any Advice? A: Observe UIKeyboardDidHideNotification: [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide:) name:UIKeyboardDidHideNotification object:nil]; - (void)keyboardDidHide:(NSNotification *)note { // Whatever you want } Don't forget to call removeObserver: in dealloc: - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; [super dealloc]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7517599", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: looking for a tool to convert PDFs to images and text (or html) I need to convert about 500 PDFs to text and images or html? A command line tool is ok, and I'm on a mac, so installable easily or with macports or brew is ideal. A: Why don't you consider using the web service Zamzar. They support conversion of pdf to html. A: You can try using Calibre, or its command-line program ebook-convert It's not always 100%, but it works for some PDF files. A: I went with installying poppler on mac and using the tools that come with it: pdftohtml pdftotext pdfimage works really well
{ "language": "en", "url": "https://stackoverflow.com/questions/7517600", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problem with Date Formatter i want to show date. I am using code NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setDateFormat:@"MMddHHmmss"]; NSDate *now = [[NSDate alloc] init]; NSString *theDate = [dateFormat stringFromDate:now]; But it shows 0921164432 PM. i dont want to show PM how can i do that A: Have you tried [dateFormat setPMSymbol:@""];? PS: As I can't reproduce the problem, I just can presume...
{ "language": "en", "url": "https://stackoverflow.com/questions/7517604", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Control.Invoke does not exist in the current context Error: The name 'Invoke' does not exist in the current context The class I am working on already has a base class so I can't have it implement something like Windows.Forms.Control. I looked at article here but I don't want to implement another interface, and don't know what I would put in the methods. This is a fairly low level C# adaptor program so it doesn't have access to the libraries most UI stuff would EDIT I'm trying to do something like this // On thread X Invoke((m_delegate)delegate(){ // Do something on main thread }); A: it's hard to tell from the little you told about your code but maybe you can use System.Threading.SynchronizationContext to do the stuff you want. You just have to capture the context in your UI-thread (for example by constructing your object there) and simulate Control.Invoke with SynchronizationContext.Post: class MyObj { SynchronizationContext _context; // please Note: construct the Objects in your main/ui thread to caputure the // right context public MyObj() { CaptureCurrentContext(); } // or call this from your main/UI thread public void CaptureCurrentContext() { _context = SynchronizationContext.Current; } public void MyInvoke(Action a) { _context.Post((SendOrPostCallback)(_ => a()), null); } } BTW: here is a very good Answer to allmost the same question: Using SynchronizationContext for sending ... A: I ended up using Action delegate with an anonymous method, that is passed in an object to the right thread, and then executed. Works great and I find this code pretty sexy.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517608", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I parse xml coming from http server using android Possible Duplicate: Parsing the XML Response in an Android Application I am using following code public void executeHttpGet() throws Exception { dialog = new ProgressDialog(this); dialog.setCancelable(true); // set a message text dialog.setMessage("Loading..."); // show it dialog.show(); BufferedReader in = null; DefaultHttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(); String url= "http://newdev.objectified.com/morris/interface/mobile.php?method=dealerLogin&username=zzzzz&password=zzzz"; String login = "zzzzz"; String pass = "zzzzz"; client.getCredentialsProvider().setCredentials(new AuthScope("newdev.objectified.com", 80), new UsernamePasswordCredentials(login, pass)); request.setURI(new URI(url)); HttpResponse response = client.execute(request); in = new BufferedReader (new InputStreamReader(response.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) { sb.append(line + NL); } in.close(); String page = sb.toString(); Toast.makeText(this, page, Toast.LENGTH_LONG).show(); // dialog.dismiss(); } Now I want to parse the coming xml which is <?xml version="1.0"?> <response> <sid>kjdci120ts32e30akcj42acaf0</sid> <dnumber>dealer</dnumber> <dtitle>Test User</dtitle> <dcity>karachi</dcity> <dprovince>sindh</dprovince> <dcountry></dcountry> </response> Please help A: Use SAX, or the DOM, or the XmlPullParser, all of which are available in Android.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517609", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Aligning a 100% width div to a fixed width div Consieder the following please: .d1 { width: 100px; float: left; } .d2 { width: auto; float: left; } <div class="d1">Content fixed</div> <div class="d2">This content should take the rest of the page (on vertical side)</div> This does not work. How can I let a fixed width div stay on the left of a variable (window adaptive) width div? Thank you. A: One way is to give the .d2 a position:absolute, then a left:100px and a right:0; Example: http://jsfiddle.net/La6QP/ A: Removing the float from .d2 and giving it a left padding equivalent to .d1's width will do the trick: .d1 { float: left; width: 100px; } .d2 { padding-left: 100px; } You can see it in action here. A: Instead of width:auto try width: 100% (or 90% / 99% etc) for the larger div. A: Just remove your current styling from d2 and give it some margin.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517614", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What actually breaks in a new Firefox update? With Firefox and its new "release every 6 weeks" strategy it seems that a large group of people are angered by this because they say "it updates too fast". However the next sentence is "I moved to Chrome" which has an even faster release cycle... This makes me wonder, what breaks in Firefox that doesn't break in Chrome? Chrome seems to have an update every day yet people don't complain. Chrome seems to of somehow been made into a stable target even with a very rapid release cycle Whats the cause? * *Does the API change substantially between every release breaking most addons? How does chrome deal with this problem? Does its API never change? *Is the Addon Compatibility Check too strict causing addons to be disabled when they really should work? Does Chrome even have an Addon compatibility check? *Are addon developers too conservative in their version compatibility definitions? *Is it simply because Firefox tells you when its updating vs Chrome which just randomly updates (arguably a worse idea)? *Are people just using ancient addons that haven't been updated in years and blaming Mozilla? How does Chrome not have this issue? Please, add any reasons you can think of if they aren't listed here. A: Before this question is closed I'll try to add some facts. Firefox doesn't have an API as such - the browser is built using the same technologies as what an add-on would use so add-ons can theoretically change almost anything. And almost any change to Firefox could break some add-on out there. This is obviously a problem and the reason why the add-on SDK was created - a limited API for simple add-ons (very much like what Chrome has). At the moment, not too many add-ons use it however. The "compatibility check" is based on what is specified in the add-on metadata. Chrome has a similar compatibility check. The important difference is that Chrome doesn't force you to specify compatibility boundaries (that's not a problem given how simple their API is). Firefox add-ons that want to be accepted on addons.mozilla.org however have to specify a maxVersion and use a version number that is already released. It can be easily updated later if no compatibility issues with the newer versions are found but most add-on authors don't do it. Starting with Firefox 6 (I think) addons.mozilla.org does some automated compatibility checks based on the change list. maxVersion for add-ons that are found compatible with the latest Beta is increased automatically. This actually works pretty well, there are no problems with the majority of popular add-ons (and they notify the authors when they do find problems). Now there are lots of add-ons that aren't popular and those sometimes do very questionable things - so those often aren't quite as lucky. But people use those as well, that's why you hear so many complains. The new release cycle actually has advantages for add-on authors: there is a fixed schedule and you know that you have 18 weeks before a particular change hits a release build. Theoretically, that's plenty of time to do testing. Practically however many add-ons are pretty much abandoned and changes are only made if a sufficient number of users complains. I'm pretty sure that it is similar with Chrome add-ons but its specifics (no explicit compatibility boundaries) make the issue less obvious.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517615", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: CrystalReports 2008 and PHP again I am confused with Windows (and it's not even Vista!). I'm trying to hook up CrystalReports 2008 and PHP for a simple report printing interface. CrystalReports (to my knowledge) provides a COM interface to open reports and then for example export them to PDF or Excel files. I'm currently calling using this method, which works fine! $ObjectFactory = new COM ( 'CrystalReports12.ObjectFactory.1' ); However after that I'm failing to initialize the DesignRuntime using this code: $ObjectFactory->CreateObject("CrystalDesignRunTime.Application"); The error I am receiving is (just like you'd expect from Windows) more than cryptic: <b>Source:</b> Unknown<br/><b>Description:</b> Unknown Any ideas? The guys over at SAP never seem to have heard of PHP, so there is not much help to find there. A: You need to install the Crystal Report Visual Studio Developers Version. This will install the "CrystalDesignRunTime.Application" object that you are referencing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517617", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to define typemap(in) and typemap(out) for const_iterator * in swig/python? I'd like to let swig know about the type of my const_iterators so that it can GC them and get rid of this error: swig/python detected a memory leak of type 'MyClass::const_iterator *', no destructor found I can't really figure out how I'm supposed to go from python to C++ and then back using the typemap(in) and typemap(out) directives. I can use these objects fine inside of python, but I guess I'm missing something essential about pointers swig and the C-API.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517618", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Button Handle MouseLeftButtonDown but still want the event to bubble I have a listbox with a DataTemplate for the items. Inside my template, I have a label and 3 buttons. My problem is that when i click the buttons, the listboxitem never become selected since the button handles the event. Is there a way I could make the event still bubble up the tree so my listboxitem become selected and still fire the click on the button? A: Put this in your ListBox.Resources <Style TargetType="{x:Type ListBoxItem}"> <EventSetter Event="PreviewGotKeyboardFocus" Handler="SelectCurrentItem"/> </Style> And this in the Code Behind protected void SelectCurrentItem(object sender, KeyboardFocusChangedEventArgs e) { ListBoxItem item = (ListBoxItem)sender; item.IsSelected = true; } You could use the following code as well which doesn't use code-behind, however it only keeps the ListBoxItem selected for as long as it has KeyBoard focus. Once focus leaves, the item becomes unselected <Style TargetType="ListBoxItem"> <Style.Triggers> <Trigger Property="IsKeyboardFocusWithin" Value="True"> <Setter Property="IsSelected" Value="True" /> </Trigger> </Style.Triggers> </Style>
{ "language": "en", "url": "https://stackoverflow.com/questions/7517620", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How could I display a heatmap on an image with PHP? I have an image (graph) inside a <div> on which accumulated clicks are displayed, so it looks like a mess of dots all over the place. I'd like to make this "nicer" to look at, and thought heatmaps would be the best option. How could I implement such a solution? I'm not particularly adept with PHP or javascript, so any pointers would help. A: In terms of accumulating clicks, you could simply register a click handler in JS that would work out where on the image the click event occurred. You could then use AJAX (or an alternative method of your choice) to return these clicks to your webserver, and presumably store them somehow. With regards to creating heatmaps, you have two potential routes. * *You could generate a heatmap image server-side in PHP, using a library such as GD or ImageMagick, and lay this image over your graph. This has the upside of not worrying about browser compatibility with the various JS solutions, but it will mean increased server load. *You could also generate the heatmap client-side in JS - there are a whole host of possible ways of doing this. This has the nice upside of leaving the hard work to the browser, keeping your server running smoothly. However, you may face issues with browser compatibility. In order to fully answer this question, it would be helpful to know a little more about what you have already, what constraints you're placed under, and whether you have any preference as to techniques used! A: * *First with the jQuery library, you can choose the position when the user mouse click gives you can see an example URL *Second you must submit this information to constantly mind your server, small packets that indicate: IP or user, date of event, position the mouse, an object that was clicked, page. *Third, you can create a arlgoritmo for example add up all the clicks of a list-based and you intence color and size of the circles (if you use these) *Fourth can make an image with PHP GD library, or you can think of creating overlays CSS properties such as brightness or shades according to the data warehouse
{ "language": "en", "url": "https://stackoverflow.com/questions/7517623", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I convert functions that use C++ pass-by-reference into C? I have a piece of code that is written in C++ and need it in C. I converted most of it but I can't figure out how to convert C++ pass-by-reference in functions to C code, i.e. Example: int& a; it is used in some function as a input variable: void do_something(float f, char ch, int& a) When I compile it with C I get compiler errors. Whats the correct way to replace the pass by references in C? A: The way to do this in C is to pass by pointer: void do_something(float f, char ch, int* a) Also when using a in do_something instead of void do_something(float f, char ch, int& a) { a = 5; printf("%d", a); } You now need to dereference a void do_something(float f, char ch, int* a) { *a = 5; printf("%d", *a); } And when calling do_something you need to take the address of what's being passed for a, so instead of int foo = 0; d_something(0.0, 'z', foo); You need to do: int foo = 0; d_something(0.0, 'z', &foo); to get the address of (ie the pointer to) foo. A: Because references are not available in C, you'll have to pass a pointer instead: void do_something(float f, char ch, int *a) And then in the body of the function you must dereference it in order to get or modify the pointed to value: *a = 5; Assuming that x in an int, and you want to call the function, you use the & operator to get its address (convert it to an int * pointer): do_something(f, ch, &x) A: The closest equivalent is a pointer: do_something(float f, char ch, int* a) Having done this, you'll need to change a -> *a everywhere within the function, and change calls to the function to pass &a instead of a. A: The "easy", but inadvisable, way is to get help from a helper pointer variable and a #definefeel free to downvote this answer! I would if I could :) Turn this int foo(int &a) { a = 42; /* ... */ return 0; } into int foo(int *tmpa) { /* & to *; rename argument */ #define a (*tmpa) /* define argument to old variable */ a = 42; /* no change */ /* ... */ /* no change */ return 0; /* no change */ #undef a /* "undo" macro */ } Note: the introduction of the #define must be done with care A: There's no equivalent to C++ references in C. However, you could use pointers. They are however variables with their own address, whereas C++ references are just aliases. function do_something(float f, char ch, int* a)
{ "language": "en", "url": "https://stackoverflow.com/questions/7517625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Cakephp SQL Error: 1064: Have a find call on a table called Attachment which is assiciated with another table called AddOn. I get a sql error. It seems to be looking for a field called display_field but this is not in the table. Why it is looking for it I do not know. $previous = $this->AddOn->Attachment->find('first', array('conditions'=> array('model'=>'AddOn', 'foreign_key'=>$id))); Error: SQL Error: 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'display' at line 1 [CORE/cake/libs/model/datasources/dbo_source.php, line 684] Query: display Array ( [Attachment] => Array ( [id] => 44 [model] => AddOn [foreign_key] => 41 [dirname] => img [basename] => fontgame_620x432.png [checksum] => 0488620c807cfaebb17489cb9c33f4fe [alternative] => Fontgame-620x432 [group] => attachment [created] => 2011-09-22 14:04:35 [modified] => 2011-09-22 14:04:35 [file] => /home/t553788/public_html/res360/res/app/webroot/Media/transfer/img/fontgame_620x432.png [ratio] => 1.43518518519 [known_ratio] => √2:1 [megapixel] => 0 [quality] => 1 [width] => 620 [height] => 432 [bits] => 8 [size] => 176726 [mime_type] => image/png ) [AddOn] => Array ( [id] => 41 [add_on_category_id] => 6 [title] => new addon [description] => qwedwed [enabled] => 0 [list_no] => 0 [availability] => 1 [price_quote_as] => 0 [price] => 10.00 [valid_from] => 2011-09-01 [valid_to] => 2011-09-02 [created] => 2011-09-20 18:22:51 [updated] => 2011-09-22 16:29:38 [deleted] => 0 [display_field] => *missing* ) ) Attachment model: <?php class Attachment extends AppModel { var $name = 'Attachment'; var $actsAs = array('Containable'); } ?> Addon Model; <?php class AddOn extends AppModel { var $name = 'AddOn'; var $actsAs = array('Containable'); var $belongsTo = array( 'AddOnCategory' => array('className' => 'AddOnCategory') ); var $hasMany = array( 'AddOnPurchase' => array('className' => 'AddOnPurchase'), 'AddOnRateroom' => array('className' => 'AddOnRateroom'), 'Attachment' => array( 'className' => 'Media.Attachment', 'foreignKey' => 'foreign_key', 'conditions' => array('Attachment.model' => 'AddOn'), 'dependent' => true ) ); /* var $validate = array( 'file' => array('mimeType' => array('rule' => array('checkMimeType', false, array( 'image/jpeg', 'image/png')))) );*/ // before find function beforeFind($queryData){ if(!isset($queryData['conditions']['AddOn.deleted'])){ $queryData['conditions']['AddOn.deleted'] = 0; } return $queryData; } } ?> A: The SQL query being performed is: display As you know, the SQL query you are looking for should start like: SELECT <something> FROM ... This one clearly doesn't and that is what MySQL is trying to tell you. Check you aren't calling a method called display() from any of your code: $this->display(); // in models or behaviors $this->Attachment->display(); // in controller, etc CakePHP tends to do this when you call a missing method on a model. A common culprit is thinking you have included a behavior by setting the model property $actAs when the correct property is actually called $actsAs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517628", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I escape slashes and double and single quotes in sed? From what I can find, when you use single quotes everything inside is considered literal. I want that for my substitution. But I also want to find a string that has single or double quotes. For example, sed -i 's/"http://www.fubar.com"/URL_FUBAR/g' I want to replace "http://www.fubar.com" with URL_FUBAR. How is sed supposed to recognize my // or my double quotes? Thanks for any help! EDIT: Could I use s/\"http\:\/\/www\.fubar\.\com\"/URL_FUBAR/g ? Does \ actually escape chars inside the single quotes? A: Regarding the single quote, see the code below used to replace the string let's with let us: command: echo "hello, let's go"|sed 's/let'"'"'s/let us/g' result: hello, let us go A: My problem was that I needed to have the "" outside the expression since I have a dynamic variable inside the sed expression itself. So than the actual solution is that one from lenn jackman that you replace the " inside the sed regex with [\"]. So my complete bash is: RELEASE_VERSION="0.6.6" sed -i -e "s#value=[\"]trunk[\"]#value=\"tags/$RELEASE_VERSION\"#g" myfile.xml Here is: # is the sed separator [\"] = " in regex value = \"tags/$RELEASE_VERSION\" = my replacement string, important it has just the \" for the quotes A: Escaping a double quote can absolutely be necessary in sed: for instance, if you are using double quotes in the entire sed expression (as you need to do when you want to use a shell variable). Here's an example that touches on escaping in sed but also captures some other quoting issues in bash: # cat inventory PURCHASED="2014-09-01" SITE="Atlanta" LOCATION="Room 154" Let's say you wanted to change the room using a sed script that you can use over and over, so you variablize the input as follows: # i="Room 101" (these quotes are there so the variable can contains spaces) This script will add the whole line if it isn't there, or it will simply replace (using sed) the line that is there with the text plus the value of $i. if grep -q LOCATION inventory; then ## The sed expression is double quoted to allow for variable expansion; ## the literal quotes are both escaped with \ sed -i "/^LOCATION/c\LOCATION=\"$i\"" inventory ## Note the three layers of quotes to get echo to expand the variable ## AND insert the literal quotes else echo LOCATION='"'$i'"' >> inventory fi P.S. I wrote out the script above on multiple lines to make the comments parsable but I use it as a one-liner on the command line that looks like this: i="your location"; if grep -q LOCATION inventory; then sed -i "/^LOCATION/c\LOCATION=\"$i\"" inventory; else echo LOCATION='"'$i'"' >> inventory; fi A: It's hard to escape a single quote within single quotes. Try this: sed "s@['\"]http://www.\([^.]\+).com['\"]@URL_\U\1@g" Example: $ sed "s@['\"]http://www.\([^.]\+\).com['\"]@URL_\U\1@g" <<END this is "http://www.fubar.com" and 'http://www.example.com' here END produces this is URL_FUBAR and URL_EXAMPLE here A: The s/// command in sed allows you to use other characters instead of / as the delimiter, as in sed 's#"http://www\.fubar\.com"#URL_FUBAR#g' or sed 's,"http://www\.fubar\.com",URL_FUBAR,g' The double quotes are not a problem. For matching single quotes, switch the two types of quotes around. Note that a single quoted string may not contain single quotes (not even escaped ones). The dots need to be escaped if sed is to interpret them as literal dots and not as the regular expression pattern . which matches any one character. A: Aside: sed expressions containing BASH variables need to be double (")-quoted for the variable to be interpreted correctly. * *https://askubuntu.com/questions/76808/how-do-i-use-variables-in-a-sed-command *How to use variables in a command in sed? If you also double-quote your $BASH variable (recommended practice) * *Bash variables, commands affected by numeric-numbered file and folder names ... then you can escape the variable double quotes as shown: sed -i "s/foo/bar ""$VARIABLE""/g" <file> I.e., replace the $VARIABLE-associated " with "". (Simply -escaping "$VAR" as \"$VAR\" results in a "-quoted output string.) Examples $ VAR='apples and bananas' $ echo $VAR apples and bananas $ echo "$VAR" apples and bananas $ printf 'I like %s!\n' $VAR I like apples! I like and! I like bananas! $ printf 'I like %s!\n' "$VAR" I like apples and bananas! Here, $VAR is "-quoted before piping to sed (sed is either '- or "-quoted): $ printf 'I like %s!\n' "$VAR" | sed 's/$VAR/cherries/g' I like apples and bananas! $ printf 'I like %s!\n' "$VAR" | sed 's/"$VAR"/cherries/g' I like apples and bananas! $ printf 'I like %s!\n' "$VAR" | sed 's/$VAR/cherries/g' I like apples and bananas! $ printf 'I like %s!\n' "$VAR" | sed 's/""$VAR""/cherries/g' I like apples and bananas! $ printf 'I like %s!\n' "$VAR" | sed "s/$VAR/cherries/g" I like cherries! $ printf 'I like %s!\n' "$VAR" | sed "s/""$VAR""/cherries/g" I like cherries! Compare that to: $ printf 'I like %s!\n' $VAR | sed "s/$VAR/cherries/g" I like apples! I like and! I like bananas! $ printf 'I like %s!\n' $VAR | sed "s/""$VAR""/cherries/g" I like apples! I like and! I like bananas! ... and so on ... Conclusion My recommendation, as standard practice, is to * *"-quote BASH variables ("$VAR") *"-quote, again, those variables (""$VAR"") if they are used in a sed expression (which itself must be "-quoted, not '-quoted) $ VAR='apples and bananas' $ echo "$VAR" apples and bananas $ printf 'I like %s!\n' "$VAR" | sed "s/""$VAR""/cherries/g" I like cherries! A: Prompt% cat t1 This is "Unix" This is "Unix sed" Prompt% sed -i 's/\"Unix\"/\"Linux\"/g' t1 Prompt% sed -i 's/\"Unix sed\"/\"Linux SED\"/g' t1 Prompt% cat t1 This is "Linux" This is "Linux SED" Prompt% A: You can use % sed -i "s%http://www.fubar.com%URL_FUBAR%g" A: What finally worked for me was to use sed's HEX option to represent: Single quote: echo "book'" |sed -n '/book[\x27]/p' book' Double quotes solution cat testfile "http://www.fubar.com" sed -i 's|"http://www\.fubar\.com"|URL_FUBAR|g' testfile cat testfile URL_FUBAR A: May be the "\" char, try this one: sed 's/\"http:\/\/www.fubar.com\"/URL_FUBAR/g' A: You need to use \" for escaping " character (\ escape the following character sed -i 's/\"http://www.fubar.com\"/URL_FUBAR/g'
{ "language": "en", "url": "https://stackoverflow.com/questions/7517632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "103" }
Q: ViewGroup finish inflate event I have created a custom layout which extends ViewGroup. Everything is working fine and I am getting the layout as expected. I want to dynamically change an element in the layout. However this is not working as I am calling it in onCreate and till that time the entire layout is not actually (drawn) inflated onto the screen and hence do not have actual size. Is there any event which can be used to find out when the inflation of the layout is done? I tried onFinishInflate but that would not work as Viewgroup has multiple views and this would be called multiple times. I am thinking of creating an interface in the Custom layout class but not sure when to fire it? A: If I understand your requirements correctly, an OnGlobalLayoutListener may give you what you need. View myView=findViewById(R.id.myView); myView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { //At this point the layout is complete and the //dimensions of myView and any child views are known. } }); A: Usually when creating a custom layout extending View or ViewGroup, you have to override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) and protected void onLayout(boolean changed, int left, int top, int right, int bottom). These are called during the process of inflation in order to obtain the size and location information related to the view. Also, subsequently, if you are extending ViewGroup you are to call measure(int widthMeasureSpec, int heightMeasureSpec) and layout(int l, int t, int r, int b) on every child view contained within. (measure() is called in onMeasure() and layout() is called in onLayout()). Anyway, in onMeasure(), you generally do something like this. @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // Gather this view's specs that were passed to it int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); int chosenWidth = DEFAULT_WIDTH; int chosenHeight = DEFAULT_HEIGHT; if(widthMode == MeasureSpec.AT_MOST || widthMode == MeasureSpec.EXACTLY) chosenWidth = widthSize; if(heightMode == MeasureSpec.AT_MOST || heightMode == MeasureSpec.EXACTLY) chosenHeight = heightSize; setMeasuredDimension(chosenWidth, chosenHeight); *** NOW YOU KNOW THE DIMENSIONS OF THE LAYOUT *** } In onLayout() you get the actual pixel coordinates of the View, so you can get the physical size like so: @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { // Android coordinate system starts from the top-left int width = right - left; int height = bottom - top; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7517636", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: List processing with intermediate state I am processing a list of strings, you can think of them as lines of a book. When a line is empty it must be discarded. When it is a title, it is "saved" as the current title. Every "normal" line must generate an object with its text and the current title. In the end you have a list of lines, each with its corresponding title. Ex.: - Chapter 1 Lorem ipsum dolor sit amet consectetur adipisicing elit - Chapter 2 sed do eiusmod tempor incididunt u First line is a title, second line must be discarded, then two lines are kept as paragraphs, each with "Chapter 1" as title. And so on. You end up with a collection similar to: {"Lorem ipsum...", "Chapter 1"}, {"consectetur...", "Chapter 1"}, {"sed do...", "Chapter 2"}, {"incididunt ...", "Chater 2"} I know the title/paragraph model doesn't make 100% sense, but I simplified the model to illustrate the problem. This is my iterative solution: let parseText allLines = let mutable currentTitle = String.Empty seq { for line in allLines do match parseLine line with | Empty -> 0 |> ignore | Title caption -> currentTitle <- caption | Body text -> yield new Paragraph(currentTitle, text) } First issue is I have to discard empty lines, I do it with 0 |> ignore but it looks quite bad to me. What is the proper to do this (without pre-filtering the list)? A tail-recursive version of this function is straightforward: let rec parseText allLines currentTitle paragraphs = match allLines with | [] -> paragraphs | head :: tail -> match head with | Empty -> parseText tail currentTitle paragraphs | Title caption -> parseText tail caption paragraphs | Body text -> parseText tail currentTitle (new Paragraph(currentTitle, text) :: tail) The question(s): * *Is there a significant difference between the two versions (style/performance/etc)? *Is there a better approach to solve this problem? Is it possible to do it with a single List.map? A: You can replace 0 |> ignore with () (unit), which is a no-op. The biggest difference between your two implementations is the first one is lazy, which might be useful for large input. The following might also work for you (it's the simplest solution I can think of): let parseText (lines:seq<string>) = lines |> Seq.filter (fun line -> line.Trim().Length > 0) |> Seq.pairwise (fun (title, body) -> Paragraph(title, body)) If not, maybe this will work: let parseText (lines:seq<string>) = lines |> Seq.choose (fun line -> match line.Trim() with | "" | null -> None | Title title -> Some title | Body text -> Some text) |> Seq.pairwise (fun (title, body) -> Paragraph(title, body)) A: Although not a single List.Map, here is the solution I came up with: let parseText allLines = allLines |> Seq.fold (fun (currentTitle,paragraphs) line -> match parseLine line with | Empty -> currentTitle,paragraphs | Title caption -> caption,paragraphs | Body text -> String.Empty,Paragraph(currentTitle, text)::paragraphs ) (String.Empty,[]) |> snd I'm using a fold with (currentTitle,paragraphs) as state. snd is used to extract the result (It is the second part of the state tuple). When you do most of your processing in F#, using lists is very tempting, but other data structures, even plain sequences have their uses. BTW, your sequence code does compile? I had to replace mutable currentTitle = String.Empty with currentTitle = ref String.Empty. A: Below is one such implementation ( although not tested, but I hope it does give you the idea ) let isNotEmpty l = match l with | Empty -> false | _ -> true let parseText allLines = allLines |> Seq.map parseLine |> Seq.filter isNotEmpty |> Seq.scan (fun (c,t,b) i -> match i with | Title tl -> (0,tl,"") | Body bb -> (1,t,bb) | _ -> (0,t,b)) (0,"","") |> Seq.filter (fun (c,_,_) -> c > 0) |> Seq.map (fun (_,t,b) -> Paragraph(t,b) )
{ "language": "en", "url": "https://stackoverflow.com/questions/7517639", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why is a linefeed char added to the http response? I do this ajax request: var response = $.ajax({ url: 'product/add', data: $("#formAddNewRow").serialize(), type: "POST", success: function() { var id = response.responseText; } }); 'product/add' is a symfony action that does some stuff. the action's view is what gets returned, for testing purpose that file looks like this: <?php echo "test"; ?> When I look at response.responseText right after success, I get "test\n". I would have expected just "test". This is what a Response Header looks like: Date Thu, 22 Sep 2011 15:17:45 GMT Server Apache/2.2.17 (Win32) mod_ssl/2.2.17 OpenSSL/0.9.8o PHP/5.3.4 mod_perl/2.0.4 Perl/v5.10.1 X-Powered-By PHP/5.3.5 Expires Thu, 19 Nov 1981 08:52:00 GMT Cache-Control no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Pragma no-cache Content-Length 5 Keep-Alive timeout=5, max=99 Connection Keep-Alive Content-Type text/html; charset=utf-8 Somewhere else I do an ajax request to url: 'product/update', it's view being exactly the same code (<?php echo "test"; ?>). But in this case response.responseTextequals "test", which is what I expect - there is no \n added. In that case, a Response Header looks like: Date Thu, 22 Sep 2011 15:27:20 GMT Server Apache/2.2.17 (Win32) mod_ssl/2.2.17 OpenSSL/0.9.8o PHP/5.3.4 mod_perl/2.0.4 Perl/v5.10.1 X-Powered-By PHP/5.3.5 Expires Thu, 19 Nov 1981 08:52:00 GMT Cache-Control no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Pragma no-cache Content-Length 4 Keep-Alive timeout=5, max=99 Connection Keep-Alive Content-Type text/html; charset=utf-8 I have not the slightest idea, why response.responseText whouldn't be the same in both cases. Why does a newline character get added to response.responseText? A: I would guess that there is a linefeed character after the final ?> Unless I am actually putting PHP inside a HTML page, I always leave off the last ?>. It isn't necessary, and tends to cause problems like this. A: Because it's part of the HTTP protocol? Response = Status-Line ; Section 6.1 *(( general-header ; Section 4.5 | response-header ; Section 6.2 | entity-header ) CRLF) ; Section 7.1 CRLF [ message-body ] ; Section 7.2
{ "language": "en", "url": "https://stackoverflow.com/questions/7517641", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I search for a value in an integer table using LIKE and ? I have a query similar to this: SELECT itemID FROM itemTable WHERE itemID LIKE '%123%' itemTable is of type INT. This query works just fine by itself, as it would select '12345' and '0912398' and so on... The problem occurs when I try to use Let's say var searchValue = 123 If I try: <cfqueryparam cfsqltype='cf_sql_integer' value="'%#searchValue#%'" > I get *Invalid data '123' for CFSQLTYPE CF_SQL_INTEGER.* If I try: <cfqueryparam cfsqltype='cf_sql_varchar' value="'%#searchValue#%'" > I get java.lang.Integer cannot be cast to java.lang.String I've tried using CAST in my SQL, and also using toString(searchValue) in various places, but I always end up with one of the error messages above. Is there any way to search and integer table using CFQUERYPARAM? EDIT: Below is the actual code I am trying to use... CFSCRIPT Code: var searchValue=123; searchFilterQuery(qry=qItemResults, field="itemID", value=searchValue,cfsqltype="cf_sql_varchar"); CFC Function: <!--- FILTER A QUERY WITH SEARCH TERM ---> <cffunction name="searchFilterQuery" access="public" returntype="query" hint="Filters a query by the given value" output="false"> <!--- ************************************************************* ---> <cfargument name="qry" type="query" required="true" hint="Query to filter"> <cfargument name="field" type="string" required="true" hint="Field to filter on"> <cfargument name="value" type="string" required="true" hint="Value to filter on"> <cfargument name="cfsqltype" type="string" required="false" default="cf_sql_varchar" hint="The cf sql type of the value."> <!--- ************************************************************* ---> <cfset var qryNew = QueryNew("")> <cfquery name="qryNew" dbtype="query"> SELECT * FROM arguments.qry WHERE #trim(arguments.field)# LIKE <cfqueryparam cfsqltype="#trim(arguments.cfsqltype)#" value="#trim(arguments.value)#"> </cfquery> <cfreturn qryNew> </cffunction> A: You need to do this, I reckon: * *remove the quotes as people have said *use a VARCHAR param, not an INTEGER, as the % symbols make the value you're passing not an INTEGER *CAST the integer column as a VARCHAR on the DB side of things. The DB could possibly do this automatically for you, but I reckon it's better to be explicit about these things. SELECT itemID FROM itemTable WHERE CAST(itemId AS VARCHAR) LIKE <cfqueryparam cfsqltype='cf_sql_varchar' value="%#searchValue#%"> A: If you take your apostrophes off the one using varchar, that will work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517643", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Calling static method in PHP 5.3 Late Static Binding Singleton Method I have an abstract class that contains these methods: <?php public static function getInstance() { $me = get_called_class(); if (!isset(self::$_instances[$me])) { $ref = new ReflectionClass($me); self::$_instances[$me] = $reflection_object->newInstance(); self::$_instances[$me]->init(); } return self::$_instances[$me]; } public function __construct() { $me = get_class($this); if(isset(self::$_instances[$me])) { throw new Exception('The singleton class has already been instantiated!'); } else { self::$_instances[$me] = $this; $this->_className = $me; } } It works exactly as I had expected when instantiating within sibling singletons. I am having an issue when attempting to get an instance from a child class that does not share the same superclass. My stack trace is: Fatal error: Call to undefined method Keywords_AdminMenu_OptionsTable::init() in D:\webroot\domains\dev.slbmeh.com\htdocs\wordpress\wp-content\plugins\LocalGiant_WPF\library\LocalGiant\Module\Abstract.php on line 149 Call Stack: 0.0012 331664 1. {main}() D:\webroot\domains\dev.slbmeh.com\htdocs\wordpress\wp-admin\admin.php:0 0.7772 3224864 2. do_action() D:\webroot\domains\dev.slbmeh.com\htdocs\wordpress\wp-admin\admin.php:151 0.7774 3225792 3. call_user_func_array() D:\webroot\domains\dev.slbmeh.com\htdocs\wordpress\wp-includes\plugin.php:405 0.7774 3225808 4. Keywords_AdminMenu->showMenu() D:\webroot\domains\dev.slbmeh.com\htdocs\wordpress\wp-includes\plugin.php:405 0.7796 3227016 5. Keywords_AdminMenu_View::showMenu() D:\webroot\domains\dev.slbmeh.com\htdocs\wordpress\wp-content\plugins\LocalGiant_WPF\modules\Keywords\AdminMenu.php:29 0.7821 3240776 6. Keywords_AdminMenu_OptionsTable->prepareItems() D:\webroot\domains\dev.slbmeh.com\htdocs\wordpress\wp-content\plugins\LocalGiant_WPF\modules\Keywords\AdminMenu\View.php:25 0.7822 3241824 7. LocalGiant_Module_Abstract->getInstance() D:\webroot\domains\dev.slbmeh.com\htdocs\wordpress\wp-content\plugins\LocalGiant_WPF\modules\Keywords\AdminMenu\OptionsTable.php:90 The init() method is an abstract method in the Singleton superclass. The class Keywords_AdminMenu_OptionsTable is a subclass of a class from a separate set of libraries, WP_List_Table from WordPress. A broken down copy of the class Keywords_AdminMenu_Options table is as follows: <?php class Keywords_AdminMenu_OptionsTable extends WP_List_Table { public function __construct(){ global $status, $page; //Set parent defaults parent::__construct( array( 'singular' => 'module', 'plural' => 'modules', 'ajax' => false ) ); } function prepareItems() { /* SNIP - Prepare my SQL query. */ $moduleDatabase = Database_Module::getInstance(); $current_page = $this->get_pagenum(); $keywords = $moduleDatabase->simpleQuery($sql, $moduleLoader->getMyNamespace()); /* SNIP - Handle my SQL data. */ } } The contents of WP_List_Table found here: http://core.trac.wordpress.org/browser/tags/3.2.1//wp-admin/includes/class-wp-list-table.php A: It turns out my code did not have getInstance declared static. This snippet of code gives a little more insight to how the static bindings affect the bindings. <pre><?php class Singleton_Super { protected static $_instances = array(); protected $_className; public function singletonSuperTest() { $getCalled = get_called_class(); $getClass = get_class($this); $getName = $this->_className; echo "\nSingleton_Super::singletonSuperTest()\n"; echo "\tget_called_class() = $getCalled\n"; echo "\tget_class(\$this) = $getClass\n"; echo "\t_className() = $getName\n"; } public function whatsMyName() { echo "\nSingleton_Super::whatsMyName()\n\t$this->_className\n"; } public static function getInstance() { $me = get_called_class(); echo "\nSingleton_Super::getInstance()\n\tget_called_class() = $me\n"; if (!isset(self::$_instances[$me])) { $ref = new ReflectionClass($me); self::$_instances[$me] = $ref->newInstance(); } return self::$_instances[$me]; } public function __construct() { $me = get_class($this); echo "\nSingleton_Super::__construct()\n\tget_called_class() = $me\n"; if(isset(self::$_instances[$me])) { throw new Exception("The Singleton class, '$me', has already been instantiated."); } else { self::$_instances[$me] = $this; $this->_className = $me; } } public function __clone() { trigger_error("Cloning is not allowed.", E_USER_ERROR); } public function __wakeup() { trigger_error("Unserializing is not allowed.", E_USER_ERROR); } } class Singleton_Child extends Singleton_Super { public function singletonTest() { $getCalled = get_called_class(); $getClass = get_class($this); $getName = $this->_className; echo "\nSingleton_Child::singletonTest()\n"; echo "\tget_called_class() = $getCalled\n"; echo "\tget_class(\$this) = $getClass\n"; echo "\t_className() = $getName\n"; } } class Outer_Concrete_Super { protected $_className; public function __construct() { $me = get_class($this); $this->_className = $me; echo "\nOuter_Concrete_Super::__construct()\n\tget_class(\$this) = $me\n"; } public function whatsMyName() { echo $this->_className; } public function concreteSuperTest() { $getCalled = get_called_class(); $getClass = get_class($this); $getName = $this->_className; echo "\nOuter_Concrete_Super::concreteSuperTest()\n"; echo "\tget_called_class() = $getCalled\n"; echo "\tget_class(\$this) = $getClass\n"; echo "\t_className() = $getName\n"; } public function superUseSingletonChild() { $singleton = Singleton_Child::getInstance(); $singleton->singletonTest(); } } class Outer_Concrete_Child extends Outer_Concrete_Super { public function concreteTest() { $getCalled = get_called_class(); $getClass = get_class($this); $getName = $this->_className; echo "\nOuter_Concrete_Super::concreteSuperTest()\n"; echo "\tget_called_class() = $getCalled\n"; echo "\tget_class(\$this) = $getClass\n"; echo "\t\$_className = $getName\n"; } public function bigTest() { $singleton = Singleton_Child::getInstance(); $singleton->whatsMyName(); $singleton->singletonSuperTest(); $singleton->singletonTest(); } } echo "\n*****************************\n"; echo "* Constructors *\n"; echo "*****************************\n\n"; $singleP = Singleton_Super::getInstance(); $singleC = Singleton_Child::getInstance(); $outerP = new Outer_Concrete_Super; $outerC = new Outer_Concrete_Child; echo "\n*****************************\n"; echo "* Third Party Class Testing *\n"; echo "*****************************\n\n"; $outerP->concreteSuperTest(); $outerC->concreteSuperTest(); $outerC->concreteTest(); $outerC->bigTest(); echo "\n*****************************\n"; echo "* Singleton *\n"; echo "*****************************\n\n"; $singleP->whatsMyName(); $singleP->singletonSuperTest(); $singleC->whatsMyName(); $singleC->singletonSuperTest(); $singleC->singletonTest(); ?> </pre> Returns the result: ***************************** * Constructors * ***************************** Singleton_Super::getInstance() get_called_class() = Singleton_Super Singleton_Super::__construct() get_called_class() = Singleton_Super Singleton_Super::getInstance() get_called_class() = Singleton_Child Singleton_Super::__construct() get_called_class() = Singleton_Child Outer_Concrete_Super::__construct() get_class($this) = Outer_Concrete_Super Outer_Concrete_Super::__construct() get_class($this) = Outer_Concrete_Child ***************************** * Third Party Class Testing * ***************************** Outer_Concrete_Super::concreteSuperTest() get_called_class() = Outer_Concrete_Super get_class($this) = Outer_Concrete_Super _className() = Outer_Concrete_Super Outer_Concrete_Super::concreteSuperTest() get_called_class() = Outer_Concrete_Child get_class($this) = Outer_Concrete_Child _className() = Outer_Concrete_Child Outer_Concrete_Super::concreteSuperTest() get_called_class() = Outer_Concrete_Child get_class($this) = Outer_Concrete_Child $_className = Outer_Concrete_Child Singleton_Super::getInstance() get_called_class() = Singleton_Child Singleton_Super::whatsMyName() Singleton_Child Singleton_Super::singletonSuperTest() get_called_class() = Singleton_Child get_class($this) = Singleton_Child _className() = Singleton_Child Singleton_Child::singletonTest() get_called_class() = Singleton_Child get_class($this) = Singleton_Child _className() = Singleton_Child ***************************** * Singleton * ***************************** Singleton_Super::whatsMyName() Singleton_Super Singleton_Super::singletonSuperTest() get_called_class() = Singleton_Super get_class($this) = Singleton_Super _className() = Singleton_Super Singleton_Super::whatsMyName() Singleton_Child Singleton_Super::singletonSuperTest() get_called_class() = Singleton_Child get_class($this) = Singleton_Child _className() = Singleton_Child Singleton_Child::singletonTest() get_called_class() = Singleton_Child get_class($this) = Singleton_Child _className() = Singleton_Child Where if you change the binding on getInstance from static you receive a result of: ***************************** * Constructors * ***************************** Singleton_Super::getInstance() get_called_class() = Singleton_Super Singleton_Super::__construct() get_called_class() = Singleton_Super Singleton_Super::getInstance() get_called_class() = Singleton_Child Singleton_Super::__construct() get_called_class() = Singleton_Child Outer_Concrete_Super::__construct() get_class($this) = Outer_Concrete_Super Outer_Concrete_Super::__construct() get_class($this) = Outer_Concrete_Child ***************************** * Third Party Class Testing * ***************************** Outer_Concrete_Super::concreteSuperTest() get_called_class() = Outer_Concrete_Super get_class($this) = Outer_Concrete_Super _className() = Outer_Concrete_Super Outer_Concrete_Super::concreteSuperTest() get_called_class() = Outer_Concrete_Child get_class($this) = Outer_Concrete_Child _className() = Outer_Concrete_Child Outer_Concrete_Super::concreteSuperTest() get_called_class() = Outer_Concrete_Child get_class($this) = Outer_Concrete_Child $_className = Outer_Concrete_Child Singleton_Super::getInstance() get_called_class() = Outer_Concrete_Child Outer_Concrete_Super::__construct() get_class($this) = Outer_Concrete_Child Outer_Concrete_Child Fatal error: Call to undefined method Outer_Concrete_Child::singletonSuperTest() in C:\inetpub\vhosts\BetterOffLocal.com\httpdocs\wp-content\plugins\LocalGiant_WPF\Singleton-Test.php on line 128 I hope this answer helps somebody out. Or at least gives insight as to how to go about troubleshooting such a problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517645", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: XCode 4 "add build setting condition" not enabled I am trying to include Layar Player in the iPhone application I am developing in XCode 4. One of the steps of section "1.3.1.2 Universal build configuration" asks to click on "Add Build Setting Condition". But that option is not enabled (it is shown in grey). Only the "Add User-defined Setting" is enabled. How can I make this option to be enabled or what could be wrong? A: To enable the Add Build Setting Condition menu item in Xcode 4, you must select a specific build configuration for a build setting. Click the disclosure triangle next to the build setting to see the build configurations, which should be Debug and Release. When you move the cursor over a build configuration or select the configuration, a small + button should appear next the name of the build configuration. Click the + button to add a conditional build setting.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517647", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Hide/Show Map Markers I wonder whether someone can help please. I'm trying to put together a script which hides and shows locations on my map. The host code I've been using is here and my code is shown below: !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml"> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> <title>Google Maps Javascript API v3 Example: Marker Categories</title> <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> <title>Google Maps</title> <style type="text/css"> html, body { height: 100%; } </style> <script type="text/javascript"> var customIcons = { "Artefact": { icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png', shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png' }, "Coin": { icon: 'http://labs.google.com/ridefinder/images/mm_20_green.png', shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png' }, "Jewellery": { icon: 'http://labs.google.com/ridefinder/images/mm_20_yellow.png', shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png' }, "Precious Metal": { icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png', shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png' } }; // this variable will collect the html which will eventually be placed in the side_bar var side_bar_html = ""; var gmarkers = []; var map = null; var infowindow = new google.maps.InfoWindow( { // A function to create the marker and set up the event window function createMarker(point,findname,html,findcategory) { var contentString = html; var marker = new google.maps.Marker({ position: point, var icon = customIcons[findcategory], shadow: iconShadow, map: map, title: findname, zIndex: Math.round(latlng.lat()*-100000)<<5 }); // === Store the category and name info as a marker properties === marker.mycategory = findcategory; marker.myname = findname; gmarkers.push(marker); google.maps.event.addListener(marker, 'click', function() { infowindow.setContent(contentString); infowindow.open(map,marker); }); } // == shows all markers of a particular category, and ensures the checkbox is checked == function show(findcategory) { for (var i=0; i<gmarkers.length; i++) { if (gmarkers[i].mycategory == findcategory) { gmarkers[i].setVisible(true); } } // == check the checkbox == document.getElementById(findcategory+"box").checked = true; } // == hides all markers of a particular category, and ensures the checkbox is cleared == function hide(findcategory) { for (var i=0; i<gmarkers.length; i++) { if (gmarkers[i].mycategory == findcategory) { gmarkers[i].setVisible(false); } } // == clear the checkbox == document.getElementById(findcategory+"box").checked = false; // == close the info window, in case its open on a marker that we just hid infowindow.close(); } // == a checkbox has been clicked == function boxclick(box,findcategory) { if (box.checked) { show(findcategory); } else { hide(findcategory); } // == rebuild the side bar makeSidebar(); } function myclick(i) { google.maps.event.trigger(gmarkers[i],"click"); } // == rebuilds the sidebar to match the markers currently displayed == function makeSidebar() { var html = ""; for (var i=0; i<gmarkers.length; i++) { if (gmarkers[i].getVisible()) { html += '<a href="javascript:myclick(' + i + ')">' + gmarkers[i].myname + '<\/a><br>'; } } document.getElementById("side_bar").innerHTML = html; } function initialize() { var myOptions = { zoom:6, center: new google.maps.LatLng(54.312195845815246,-4.45948481875007), mapTypeId: google.maps.MapTypeId.TERRAIN } map = new google.maps.Map(document.getElementById("map"), myOptions); google.maps.event.addListener(map, 'click', function() { infowindow.close(); }); // Read the data downloadUrl("loadpublicfinds.php", function(data) { var xml = data.responseXML; var markers = xml.documentElement.getElementsByTagName("marker"); for (var i = 0; i < markers.length; i++) { // obtain the attribues of each marker var lat = parseFloat(markers[i].getAttribute("findosgb36lat")); var lng = parseFloat(markers[i].getAttribute("findosgb36lon")); var point = new google.maps.LatLng(lat,lng); var findname = markers[i].getAttribute("findname"); var finddescription = markers[i].getAttribute("finddescription"); var html = "<b>" + 'Find : ' + "</b>" + findname + "<p>" + "<b>" + 'Description: ' + "</b>" + finddescription + "</p>" var findcategory = markers[i].getAttribute("findcategory"); // create the marker var marker = createMarker(point,findname,html,findcategory); } // == show or hide the categories initially == show("Artefact"); hide("Coin"); hide("Jewellery"); hide("Precious Metal"); // == create the initial sidebar == makeSidebar(); }); } </script> </head> <body style="margin:0px; padding:0px;" onload="initialize()"> <!-- you can use tables or divs for the overall layout --> <table border=1> <tr> <td> <div id="map" style="width: 550px; height: 450px"></div> </td> <td valign="top" style="width:150px; text-decoration: underline; color: #4444ff;"> <div id="side_bar"></div> </td> </tr> </table> <form action="#"> Artefact: <input type="checkbox" id="Artefactbox" onclick="boxclick(this,'Artefact')" /> &nbsp;&nbsp; Coin: <input type="checkbox" id="Coinbox" onclick="boxclick(this,'Coin')" /> &nbsp;&nbsp; Jewellery: <input type="checkbox" id="Jewellerybox" onclick="boxclick(this,'Jewellery')" /><br /> Precious Metal: <input type="checkbox" id="PreciousMetalbox" onclick="boxclick(this,'Precious_Metal')" /><br /> </form> </body> </html> When I try and run my code I get the following error: Message: Expected identifier, string or number Line: 42 Char: 1 The line which it points to is this function createMarker(point,findname,html,findcategory) { I'm fairly new to this, but I've run the code through 'Firebug' and it states that the line id 'missing: propertyid' but I must admit I'm not sure what this means. I just wondered whether someone could take a look at this please and let me know where I'm going wrong. Many thanks UPDATED CODE <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Map My Finds - Public Finds</title> <link rel="stylesheet" href="css/publicfinds.css" type="text/css" media="all" /> <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&language=en"></script> <script type="text/javascript"> var customIcons = { "Artefact": { icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png', shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png' }, "Coin": { icon: 'http://labs.google.com/ridefinder/images/mm_20_green.png', shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png' }, "Jewellery": { icon: 'http://labs.google.com/ridefinder/images/mm_20_yellow.png', shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png' }, "Precious Metal": { icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png', shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png' } }; // this variable will collect the html which will eventually be placed in the side_bar var side_bar_html = ""; var gmarkers = []; var markers; var infowindow = new google.maps.InfoWindow(); function createMarker(latlng,name,html,category) { var contentString = html; var marker = new google.maps.Marker({ position: point, icon: customIcons[findcategory], shadow: iconShadow, map: map, title: findname, zIndex: Math.round(latlng.lat()*-100000)<<5 }); // === Store the category and name info as a marker properties === marker.mycategory = findcategory; marker.myname = findname; gmarkers.push(marker); google.maps.event.addListener(marker, 'click', function() { infowindow.setContent(contentString); infowindow.open(map,marker); }); // == shows all markers of a particular category, and ensures the checkbox is checked == function show(findcategory) { for (var i=0; i<gmarkers.length; i++) { if (gmarkers[i].mycategory == findcategory) { gmarkers[i].setVisible(true); } } // == check the checkbox == document.getElementById(findcategory+"box").checked = true; } // == hides all markers of a particular category, and ensures the checkbox is cleared == function hide(findcategory) { for (var i=0; i<gmarkers.length; i++) { if (gmarkers[i].mycategory == findcategory) { gmarkers[i].setVisible(false); } } // == clear the checkbox == document.getElementById(findcategory+"box").checked = false; // == close the info window, in case its open on a marker that we just hid infowindow.close(); } // == a checkbox has been clicked == function boxclick(box,findcategory) { if (box.checked) { show(findcategory); } else { hide(findcategory); } // == rebuild the side bar makeSidebar(); } function myclick(i) { google.maps.event.trigger(gmarkers[i],"click"); } // == rebuilds the sidebar to match the markers currently displayed == function makeSidebar() { var html = ""; for (var i=0; i<gmarkers.length; i++) { if (gmarkers[i].getVisible()) { html += '<a href="javascript:myclick(' + i + ')">' + gmarkers[i].myname + '<\/a><br>'; } } document.getElementById("side_bar").innerHTML = html; } function load() { var map = new google.maps.Map(document.getElementById("map"), { center: new google.maps.LatLng(54.312195845815246,-4.45948481875007), zoom:6, mapTypeId: 'terrain' }); google.maps.event.addListener(map, 'click', function() { infowindow.close(); }); // Change this depending on the name of your PHP file downloadUrl("loadpublicfinds.php", function(data) { var xml = data.responseXML; var markers = xml.documentElement.getElementsByTagName("marker"); for (var i = 0; i < markers.length; i++) { var lat = parseFloat(markers[i].getAttribute("findosgb36lat")); var lng = parseFloat(markers[i].getAttribute("findosgb36lon")); var point = new google.maps.LatLng(lat,lng); var findcategory = markers[i].getAttribute("findcategory"); var findname = markers[i].getAttribute("findname"); var finddescription = markers[i].getAttribute("finddescription"); var html = "<b>" + 'Find : ' + "</b>" + findname + "<p>" + "<b>" + 'Description: ' + "</b>" + finddescription + "</p>" var marker = createMarker(point,findname,html,findcategory); } // == show or hide the categories initially == show("Artefact"); hide("Coin"); hide("Jewellery"); hide("Precious Metal"); // == create the initial sidebar == makeSidebar(); }); } function downloadUrl(url, callback) { var request = window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest; request.onreadystatechange = function() { if (request.readyState == 4) { request.onreadystatechange = doNothing; callback(request, request.status); } }; request.open('GET', url, true); request.send(null); } function doNothing() {} } </script> </head> <body onLoad="load()"> <div id="map"></div> <!-- you can use tables or divs for the overall layout --> <form action="#"> Theatres: <input type="checkbox" id="Artefact" onclick="boxclick(this,'Artefact')" /> &nbsp;&nbsp; Golf Courses: <input type="checkbox" id="Coin" onclick="boxclick(this,'Coin')" /> &nbsp;&nbsp; Golf Courses: <input type="checkbox" id="Jewellery" onclick="boxclick(this,'Jewellery')" /> &nbsp;&nbsp; Tourist Information: <input type="checkbox" id="Precious Metal" onclick="boxclick(this,'Precious Metal')" /><br /> </form> </body> </html> A: Couple syntax errors I noticed: 1.) All of you code was wrapped in the InfoWindow object change this: var infowindow = new google.maps.InfoWindow( { to this: var infowindow = new google.maps.InfoWindow(); 2.) You are setting the icon property wrong in the marker change this: var marker = new google.maps.Marker({ position: point, var icon = customIcons[findcategory], //wont work shadow: iconShadow, map: map, title: findname, zIndex: Math.round(latlng.lat()*-100000)<<5 }); to this: var marker = new google.maps.Marker({ position: point, icon: customIcons[findcategory], shadow: iconShadow, map: map, title: findname, zIndex: Math.round(latlng.lat()*-100000)<<5 }); I was not receiving any more syntax errors in Visual Studio after making these changes. Edit to include additional fix: the downloadUrl function is not defined on this page. You did not include the script file in the head area of the page. Add this right after where the Google maps api is referenced: <script type="text/javascript" src="scripts/downloadxml.js"></script> Update Looks like you changed the name of the point parameter to latlng in the createMarker function, but did not change it everywhere inside the function. The position property is still set to point. Also it looks like you might be missing the closing bracket for the create marker function as well. function createMarker(latlng,name,html,category) { var contentString = html; var marker = new google.maps.Marker({ position: latlng, //changed from 'point' icon: customIcons[findcategory], shadow: iconShadow, map: map, title: findname, zIndex: Math.round(latlng.lat()*-100000)<<5 }); // === Store the category and name info as a marker properties === marker.mycategory = findcategory; marker.myname = findname; gmarkers.push(marker); google.maps.event.addListener(marker, 'click', function() { infowindow.setContent(contentString); infowindow.open(map,marker); }); } //is this where this function ends? I would recommend that you put all of this script into a separate file and then reference it with a <script type="text/javascript" src="path to your script" /> tag. It will make the file easier to maintain and troubleshoot in the future.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ldap check username-password combination via java To test a username-password combination with ldap i do the following * *connect to an ldap server with a masteruser account *search for the user to check *open another connection by using InitialLdapContext and the given combination. This works fine for me till i noticed that some correct combinations wont work. (these are mostly accounts which were created short time ago) Is there a way a user is listed in a ldap directory but isnt allowed to connect to the ldap server itself?! My current code just uses the masteruser to search for the username to check, but in the end its just a new connection with the username-password combination to check. Should i possibly connect with the masteruser and then bind with the username-password combination? this is the part where i check the combination: static boolean CheckLDAPConnection(String user_name, String user_password) { try { Hashtable<String, String> env1 = new Hashtable<String, String>(); env1.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env1.put(Context.SECURITY_AUTHENTICATION, "simple"); env1.put(Context.SECURITY_PRINCIPAL, user_name); env1.put(Context.SECURITY_CREDENTIALS, user_password); env1.put(Context.PROVIDER_URL, ip); try { //Connect with ldap new InitialLdapContext(env1, null); //Connection succeeded System.out.println("Connection succeeded!"); return true; } catch (AuthenticationException e) { //Connection failed System.out.println("Connection failed!"); e.printStackTrace(); return false; } } catch (Exception e) { } return false; } A: Once you have found the user's DN you should then add those credentials to the first context's environment and then try a reconnect(). That does the LDAP bind operation. A: We check user and password against LDAP by using directly its user and password to create the LDAP connection. If connection can be created, use is authorized. Then search for user permission in the LDAP with the same connection (if no permission can not access the application regarding the user is validated). Could not be the best approach but using a master-user to create the first LDAP connection is not possible in a 2-tier application (security concerns about storing the master-user in the client GUI) as in our case. Maybe you can change your approach. This approach have some disadvantages, as creating new users, so need to grant special permissions on the LDAP to an "admin" user of the GUI to create other users but don't administrate the LDAP...
{ "language": "en", "url": "https://stackoverflow.com/questions/7517650", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to select maximum per column-value in SQL? In SQL Server, I have a list of integers, datetimes, and strings. For example, number datetime string 6 2011-09-22 12:34:56 nameOne 6 2011-09-22 1:23:45 nameOne 6 2011-09-22 2:34:56 nameOne 5 2011-09-22 3:45:01 nameOne 5 2011-09-22 4:56:01 nameOne 5 2011-09-22 5:01:23 nameOne 7 2011-09-21 12:34:56 nameTwo 7 2011-09-21 1:23:45 nameTwo 7 2011-09-21 2:34:56 nameTwo 4 2011-09-21 3:45:01 nameTwo 4 2011-09-21 4:56:01 nameTwo 4 2011-09-21 5:01:23 nameTwo I would to write a SQL statement that outputs only those rows whose number is a maximum for each string. In this example, number datetime string 6 2011-09-22 12:34:56 nameOne 6 2011-09-22 1:23:45 nameOne 6 2011-09-22 2:34:56 nameOne 7 2011-09-21 12:34:56 nameTwo 7 2011-09-21 1:23:45 nameTwo 7 2011-09-21 2:34:56 nameTwo I know that I could loop over each string in the string column, then get the maximum for that string, then select the rows matching that maximum. For example, declare @max int declare my_cursor cursor fast_forward for select distinct string from table open my_cursor fetch next from my_cursor into @string while @@fetch_status = 0 begin set @max = (select max(number) from table where string = @string) select * from table where number = @max fetch next from my_cursor into @string end close my_cursor deallocate my_cursor However, I am wondering if there is a way to accomplish this task WITHOUT using a loop (e.g., by using aggregate functions and grouping). A: ;WITH T as ( SELECT *, RANK() OVER (PARTITION BY string ORDER BY number DESC) RN FROM YourTable ) SELECT number, datetime, string FROM T WHERE RN=1; A: WITH maxes AS ( SELECT string, MAX(number) AS max_number FROM tbl GROUP BY string ) SELECT tbl.* FROM tbl INNER JOIN maxes ON maxes.string = tbl.string AND maxes.max_number = tbl.number
{ "language": "en", "url": "https://stackoverflow.com/questions/7517651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: JQuery Function that hides all tags whose functions match a certain pattern I am new Jquery and have written a toggle function that looks like this: $('.one-toggle').click(function(){ $('.one-graph').toggle(); }); Basically I want to change my two CSS selectors so that they match any tag that has one-toggle and one-graph. I don't want the selector to require a direct match. Regex maybe? A: Just use the standard CSS selector separator: $('.one-toggle, .one-graph').click(function(){ $('.one-graph').toggle(); }); A: To match tags that have both class names, you just need this: // cache the selector var $elements = $('.one-toggle.one-graph').click(function(){ // toggle all matched elements $elements.toggle(); // or did you want to toggle just the clicked element? // $(this).toggle(); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7517652", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problem with executing PHP script running on Cron I'm trying to run a very simple PHP script on cron on a third-party hosting server and I have encountered a weird problem. The script's contents is NOT executed although I got confirmed that the cron does execute the script in scheduled times. I cannot check the Cron settings as it is not on my server, yet I would like to know if there is something I do wrong? The script is for testing purpose only and thus it is very simple: <?php $file = fopen("file-" . rand(1000, 9999) . '.txt', 'w'); fwrite($file, 'cron'); fclose($file); ?> When I run this script manually, the file is created. When I leave it on Cron, nothing happens. What can be the cause? The permissions of the script are 777. Do I do something wrong or is the problem on a server? Many thanks. A: Remember that a script running under cron has a very different environment than the same script being run manually on the command line. In particular, cron will have a different working directory than the shell prompt. You don't specify an absolute path for your file, so when the script is run by cron, it'll try to create that file in whatever directory is the CWD at that time. If the userid this job runs under doesn't have write permissions on that directory (or the file exists but owned by someone else), then the fopen will fail. Never assume that a file operation succeeds. Always check for error conditions. And while you're at it, specify an absolute path for the file, so you KNOW where it will be written: $filename = "/path/to/where/you/wantfile-" . rand(1000,9999) . '.txt'; $file = fopen($filename, 'w') or die("Unable to open $filename for output"); A: This probably because the script is run as some user other than apache. In some cases I will use curl and make the script check to see if the IP is the local IP to make sure it is being run from the right machine. There certainly less hackish ways to accomplish this, but this is always a quick and easy one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517656", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: problem with using twitter4j on android I am using twitter4j and oauth-signpost for integrating twitter with my android app. I have implemented part of the activity, what it does is it authenticates the user (or atleast thats what its supposed to do). The problem is, it cant find the token and gives this error message: 09-22 15:44:06.123: DEBUG/TwitterApp(363): Error getting access token 09-22 15:44:06.134: WARN/System.err(363): oauth.signpost.exception.OAuthExpectationFailedException: Request token or token secret not set in server reply. The service provider you use is probably buggy. 09-22 15:44:06.194: WARN/System.err(363): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:202) 09-22 15:44:06.194: WARN/System.err(363): at oauth.signpost.AbstractOAuthProvider.retrieveAccessToken(AbstractOAuthProvider.java:97) 09-22 15:44:06.194: WARN/System.err(363): at corp.encameo.app.TwitterApp$3.run(TwitterApp.java:139) activity code: public class TwitterActivity extends Activity { private TwitterApp mTwitter; private static final String twitter_consumer_key = "xxx"; private static final String twitter_secret_key = "xxx"; String FILENAME = "AndroidSSO_data"; private SharedPreferences mPrefs; String name=""; String bitly=""; String imageLink=""; EditText linkText; EditText descText; ImageButton backButton; public ImageLoader imageLoader; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); setContentView(R.layout.twitter); getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title3); TextView title=(TextView) findViewById(R.id.title_text_view_success3); title.setText("Share on Twitter"); imageLoader=new ImageLoader(getApplicationContext()); linkText = (EditText) findViewById(R.id.twedit11); descText = (EditText) findViewById(R.id.twedit22); linkText.setFocusable(false); mTwitter = new TwitterApp(this, twitter_consumer_key,twitter_secret_key); mTwitter.setListener(mTwLoginDialogListener); if (mTwitter.hasAccessToken()) { String username = mTwitter.getUsername(); username = (username.equals("")) ? "Unknown" : username; } else { mTwitter.authorize(); } Bundle extras = getIntent().getExtras(); if(extras !=null) { name = extras.getString("name"); bitly = extras.getString("bitly"); imageLink = extras.getString("imageLink"); } if (bitly.equalsIgnoreCase(""))bitly="http://www.encameo.com"; linkText.setText(bitly); linkText.setEnabled(false); ImageView image=(ImageView) findViewById(R.id.twicon); imageLoader.DisplayImage(imageLink, this, image); Button twButton = (Button) findViewById(R.id.twButton); twButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v){ finish(); } }); backButton = (ImageButton) findViewById(R.id.back_button3); backButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { System.out.println("!!! BACK !!!"); //finishActivity(0); onBackPressed(); } }); } private final TwDialogListener mTwLoginDialogListener = new corp.encameo.app.TwitterApp.TwDialogListener() { public void onComplete(String value) { String username = mTwitter.getUsername(); username = (username.equals("")) ? "No Name" : username; Toast.makeText(TwitterActivity.this, "Connected to Twitter as " + username, Toast.LENGTH_LONG).show(); } public void onError(String value) { Toast.makeText(TwitterActivity.this, "Twitter connection failed", Toast.LENGTH_LONG).show(); } }; } TwitterApp class: public class TwitterApp { private Twitter mTwitter; private TwitterSession mSession; private AccessToken mAccessToken; private CommonsHttpOAuthConsumer mHttpOauthConsumer; private OAuthProvider mHttpOauthprovider; private String mConsumerKey; private String mSecretKey; private ProgressDialog mProgressDlg; private TwDialogListener mListener; private Context context; public static final String CALLBACK_URL = "twitterapp://connect"; private static final String TAG = "TwitterApp"; public TwitterApp(Context context, String consumerKey, String secretKey) { this.context = context; mTwitter = new TwitterFactory().getInstance(); mSession = new TwitterSession(context); mProgressDlg = new ProgressDialog(context); mProgressDlg.requestWindowFeature(Window.FEATURE_NO_TITLE); mConsumerKey = consumerKey; mSecretKey = secretKey; mHttpOauthConsumer = new CommonsHttpOAuthConsumer(mConsumerKey, mSecretKey); mHttpOauthprovider = new DefaultOAuthProvider("https://api.twitter.com/oauth/request_token", "https://api.twitter.com/oauth/access_token", "https://api.twitter.com/oauth/authorize"); mAccessToken = mSession.getAccessToken(); configureToken(); } public void setListener(TwDialogListener listener) { mListener = listener; } @SuppressWarnings("deprecation") private void configureToken() { if (mAccessToken != null) { mTwitter.setOAuthConsumer(mConsumerKey, mSecretKey); mTwitter.setOAuthAccessToken(mAccessToken); } } public boolean hasAccessToken() { return (mAccessToken == null) ? false : true; } public void resetAccessToken() { if (mAccessToken != null) { mSession.resetAccessToken(); mAccessToken = null; } } public String getUsername() { return mSession.getUsername(); } public void updateStatus(String status) throws Exception { try { mTwitter.updateStatus(status); } catch (TwitterException e) { throw e; } } public void authorize() { mProgressDlg.setMessage("Initializing ..."); mProgressDlg.show(); new Thread() { @Override public void run() { String authUrl = ""; int what = 1; try { authUrl = mHttpOauthprovider.retrieveRequestToken(mHttpOauthConsumer, CALLBACK_URL); what = 0; Log.d(TAG, "Request token url " + authUrl); } catch (Exception e) { Log.d(TAG, "Failed to get request token"); e.printStackTrace(); } mHandler.sendMessage(mHandler.obtainMessage(what, 1, 0, authUrl)); } }.start(); } public void processToken(String callbackUrl) { mProgressDlg.setMessage("Finalizing ..."); mProgressDlg.show(); final String verifier = getVerifier(callbackUrl); new Thread() { @Override public void run() { int what = 1; try { mHttpOauthprovider.retrieveAccessToken(mHttpOauthConsumer, verifier); mAccessToken = new AccessToken(mHttpOauthConsumer.getToken(), mHttpOauthConsumer.getTokenSecret()); configureToken(); User user = mTwitter.verifyCredentials(); mSession.storeAccessToken(mAccessToken, user.getName()); what = 0; } catch (Exception e){ Log.d(TAG, "Error getting access token"); e.printStackTrace(); } mHandler.sendMessage(mHandler.obtainMessage(what, 2, 0)); } }.start(); } private String getVerifier(String callbackUrl) { String verifier = ""; try { callbackUrl = callbackUrl.replace("twitterapp", "http"); URL url = new URL(callbackUrl); String query = url.getQuery(); String array[] = query.split("&"); for (String parameter : array) { String v[] = parameter.split("="); if (URLDecoder.decode(v[0]).equals(oauth.signpost.OAuth.OAUTH_VERIFIER)) { verifier = URLDecoder.decode(v[1]); break; } } } catch (MalformedURLException e) { e.printStackTrace(); } return verifier; } private void showLoginDialog(String url) { final TwDialogListener listener = new TwDialogListener() { @Override public void onComplete(String value) { processToken(value); } @Override public void onError(String value) { mListener.onError("Failed opening authorization page"); } }; new TwitterDialog(context, url, listener).show(); } private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { mProgressDlg.dismiss(); if (msg.what == 1) { if (msg.arg1 == 1) mListener.onError("Error getting request token"); else mListener.onError("Error getting access token"); } else { if (msg.arg1 == 1) showLoginDialog((String) msg.obj); else mListener.onComplete(""); } } }; public interface TwDialogListener { public void onComplete(String value); public void onError(String value); } } any suggestions ???
{ "language": "en", "url": "https://stackoverflow.com/questions/7517657", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Grails 1.3.7 clean project cannot serve utf8 files I create a clean grails application and run grails dev war and deploy under Tomcat 6.0.32. When I attempt to download this file via localhost:8080/utf8.html, I get a response with busted encoding and characters. When I create a ROOT/ directory in web-app/ and serve the same file, the response is fine. What's going on here? A: Write a controller to serve files properly. With no other solutions, this is all you have.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: FB._https = true doesn't play nice with FB.Canvas.setAutoResize? I'm converting my facebook app to run through HTTPS. It seems like when I set the FB._https variable to true, the FB.Canvas.setAutoResize() stops resizing the iframe. This is what my code looks like: window.fbAsyncInit = function() { FB._https = true; // troublemaker FB.init({ appId: facebookAppId, status: true, cookie: true, session: facebookSession, xfbml: true }); // The parameter show how many milliseconds to wait between // resizing. // Apparently, 91 is Paul's favorite number. // http://developers.facebook.com/docs/reference/javascript/FB.Canvas.setAutoResize/ FB.Canvas.setAutoResize(91); }; Any ideas? A: If you set FB._https = true; and you access the page over http then you have trouble. I suggest using FB._https = (window.location.protocol == "https:"); per Facebook JavaScript SDK over HTTPS loading non-secure items A: * *Remove the line specifying FB._https. you should not be setting this value. The JS SDK does this on its own when it is loaded. Setting it yourself is a hack -- the underscore in the name is supposed to suggest that the value is not for external modification. *You should use a cross-domain communication channel URL. Information about this is documented on the JavaScript SDK page. When you use the channel URL, make sure not to specify a protocol like "http:" or "https:". The channel URL should begin with "//", or else it should be manually constructed based on document.location.protocol. *Make sure you have properly set a "Site URL" and "Site Domain" in the application's settings. This is crucial for various JS SDK functions. A: I'm having the same issue. It seems like it depends on where I put the connect script. Here's the code for getting SSL to work. You have to remove the connect script and go with the channelUrl. <!-- COMMENT OUT <script src="https://connect.facebook.net/en_US/all.js"></script>--> <script type="text/javascript" charset="utf-8"> FB._https = (window.location.protocol == "https:"); window.fbAsyncInit = function() { FB.init({ appId : 'xxxxxxxxxxxxx', // App ID channelUrl : '<?php echo bloginfo('url');?>/channel.html', // Channel File status : true, // check login status cookie : true, // enable cookies to allow the server to access the session oauth : true, // enable OAuth 2.0 xfbml : true // parse XFBML }); FB.Canvas.setAutoGrow(); } // Load the SDK Asynchronously (function(d){ var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0]; if (d.getElementById(id)) {return;} js = d.createElement('script'); js.id = id; js.async = true; js.src = "//connect.facebook.net/en_US/all.js"; ref.parentNode.insertBefore(js, ref); }(document)); //FB.Canvas.setAutoGrow(); /*FB.Event.subscribe('edge.create', function(response){ top.location.href = ''; }*/ Here's the code to get the ifame to re-size, but breaks ssl. Add connect script back to the top and remove channelUrl. Actually you don't have to remove the channelUrl for it to work. <script src="https://connect.facebook.net/en_US/all.js"></script> <script type="text/javascript" charset="utf-8"> FB._https = (window.location.protocol == "https:"); window.fbAsyncInit = function() { FB.init({ appId : 'xxxxxxxxxxxxxxx', // App ID //channelUrl : '<?php echo bloginfo('url');?>/channel.html', // Channel File status : true, // check login status cookie : true, // enable cookies to allow the server to access the session oauth : true, // enable OAuth 2.0 xfbml : true // parse XFBML }); FB.Canvas.setAutoGrow(); } // Load the SDK Asynchronously (function(d){ var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0]; if (d.getElementById(id)) {return;} js = d.createElement('script'); js.id = id; js.async = true; js.src = "//connect.facebook.net/en_US/all.js"; ref.parentNode.insertBefore(js, ref); }(document)); //FB.Canvas.setAutoGrow(); /*FB.Event.subscribe('edge.create', function(response){ top.location.href = ''; }*/ I don't get it. Phil
{ "language": "en", "url": "https://stackoverflow.com/questions/7517670", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Javascript: How to check the existence of a url? I need to check the whether an external url like http://www.example.com exists or not using javascript or ajax. Thanks in advance.. A: You can load it into a hidden iframe and see if you get content. You can't use "ajax" (e.g., an XMLHttpRequest call) for it, because you'll run into Same Origin Policy restrictions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517674", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Entity Framework Code First - One-to-Many with a join/link table Is it possible to create a One-to-Many relationship with Code First that uses a link/join table between them? public class Foo { public int FooId { get; set; } // ... public int? BarId { get; set; } public virtual Bar Bar { get; set; } } public class Bar { public int BarId { get; set; } // ... public virtual ICollection<Foo> Foos { get; set; } } I want this to map as follows: TABLE Foo FooId INT PRIMARY KEY ... TABLE Bar BarId INT PRIMARY KEY TABLE FooBar FooId INT PRIMARY KEY / FOREIGN KEY BarId INT FOREIGN KEY With this, I would have the ability to make sure Foo only has one Bar, but that Bar could be re-used by many different Foos. Is this possible with Entity Framework? I would prefer to not have to put the key in Foo itself because I don't want a nullable foreign key. If it is possible please provide an example using the Fluent API and not the data annotations. A: You can use Entity splitting to achieve this public class Foo { public int FooId { get; set; } public string Name { get; set; } public int BarId { get; set; } public virtual Bar Bar { get; set; } } Then in your custom DbContext class protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Foo>().HasKey(f => f.FooId); modelBuilder.Entity<Foo>() .Map(m => { m.Properties(b => new {b.Name}); m.ToTable("Foo"); }) .Map(m => { m.Properties(b => new {b.BarId}); m.ToTable("FooBar"); }); modelBuilder.Entity<Foo>().HasRequired(f => f.Bar) .WithMany(b => b.Foos) .HasForeignKey(f => f.BarId); modelBuilder.Entity<Bar>().HasKey(b => b.BarId); modelBuilder.Entity<Bar>().ToTable("Bar"); } The BarId column will be created as a not null column in FooBar table. You can check out Code First in the ADO.NET Entity Framework 4.1 for more details
{ "language": "en", "url": "https://stackoverflow.com/questions/7517675", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Key-Path for an element of a dictionary property of an object in a predicate? In short, I am looking for the correct predicate format to index into a dictionary attribute on an object. I have an array of myObject instances, each with an attribute CPDictionary(NSMutableDictionary) extAttributes and I am trying to allow filtering based on values in extAttributes. I am defining my predicate as follows [CPPredicate predicateWithFormat:@"extAttributes[%K] like[c] %@",key,val] I am not sure what the correct key-path would be for this. Reading the documentation on NSPredicate it would seem that "extAttributes[%k]" might be an index into an array, not a dictionary. I have tried several alternatives and this is the only one that doesn't error. When inspecting the resulting objects, the expressions in the predicate object appear to be correct. However, it doesn't have the intended result. A: It looks like you might be confusing array and dictionary references. Just use a key path (dot-separated element names) to refer to nested elements or object properties, conceptually something like this: [CPPredicate predicateWithFormat:@"%K like[c] %@", @"extAttributes.myNestedElementName", val]; Then again, I'm not all that familiar with Cappuccino, so I'm not sure if they've done something slightly different here, but this is the way it works in Cocoa and Cocoa touch. EDIT To compute the key dynamically, all you need to do is compose a key path string: var keyPath = [CPString stringWithFormat:@"%@.%@", @"extAttributes", key]; You can now create the predicate as follows: [CPPredicate predicateWithFormat:@"%K like[c] %@", keyPath, val]; EDIT The equivalent code in Cocoa/Cocoa touch would be: NSString *keyPath = [NSString stringWithFormat:@"%@.%@", @"extAttributes", key]; [NSPredicate predicateWithFormat:@"%K like[c] %@", keyPath, val];
{ "language": "en", "url": "https://stackoverflow.com/questions/7517677", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to translate UTF8 file into html-like notation How to translate an Unicode file in French (any language) to a relevant file in html-special encoding. For example, the letter "e" with accent should be translated into &eacute; , etc... é -> &eacute; I need to prepare a localized file without UTF8 letters like "é", only it should contain the other formatting like &eacute; A: The uniquote utility will do this for you when you use the --html and --verbose options together. $ echo niño difícil | uniquote --html --verbose ni&ntilde;o dif&iacute;cil A: php htmlentities see it on php manual
{ "language": "en", "url": "https://stackoverflow.com/questions/7517678", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do i integrate Selenium RC with PHP? I very recently started working on Selenium. I know to run the testcases on IE we should have Selenium Server. I downloaded and finally got it running on my computer. Can anyone tell me how do i put the Selenium test case from IDE to RC and integrate the RC in PHP? or how to run Selenium RC . Correct me if anything wrong in my understanding. Note: i searched everything related to Selenium RC but i dint find anything clear. U can give me any valuable link that answers my RC in PHP question. I would really appreciate your help. A: I am not sure what you mean by "Selenium test case from IDE to RC". I think you are referring to browser addon for Selenium testing. Anyhow, to integrate Selenium RC with PHP, you need PHPUnit framework which supports Selenium test cases. You need to do the following steps. * *Download and run Selenium RC server (I think you already done this, great!) *Write a selenium test case by extending to PHPUnit Selenium Test Case class. *Then run your test case as you would run any other PHPUnit test cases. Sample code for how to write a Selenium test case using PHPUnit is as follow. <?php require_once 'PHPUnit/Extensions/SeleniumTestCase.php'; class WebTest extends PHPUnit_Extensions_SeleniumTestCase { protected function setUp() { $this->setBrowser('*firefox'); $this->setBrowserUrl('http://www.example.com/'); } public function testTitle() { $this->open('http://www.example.com/'); $this->assertTitleEquals('Example Web Page'); } } ?> For more information, please refer to PHPUnit documentation on Selenium test cases. http://www.phpunit.de/manual/3.1/en/selenium.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7517680", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Rotate a Java Graphics2D Rectangle? I have searched everywhere and I just cant find the answer. How do I rotate a Rectangle in java? Here is some of my code: package net.chrypthic.Space; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Space extends JPanel implements ActionListener{ Timer time; public Space() { setVisible(true); setFocusable(true); addMouseMotionListener(new ML()); addMouseListener(new ML()); addKeyListener(new AL()); time=new Timer(5, this); time.start(); } public void paint(Graphics g) { super.paint(g); Graphics2D g2d = (Graphics2D)g; g2d.setColor(Color.WHITE); Rectangle rect2 = new Rectangle(100, 100, 20, 20); g2d.draw(rect2); g2d.fill(rect2); } public void actionPerformed(ActionEvent ae) { repaint(); } public class AL extends KeyAdapter { public void keyPressed(KeyEvent e) { } public void keyReleased(KeyEvent e) { } } public class ML extends MouseAdapter { public void mouseMoved(MouseEvent e) { } public void mousePressed(MouseEvent e){ } } } I tried g2d.rotate(100D); but it didnt work. Thanks in advance. Here's my edited code: package net.chrypthic.Space; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Space extends JPanel implements ActionListener{ Timer time; public Space() { setVisible(true); setFocusable(true); setSize(640, 480); setBackground(Color.BLACK); time=new Timer(5, this); time.start(); } public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D)g; Rectangle rect1 = new Rectangle(100, 100, 20, 20); g2d.setColor(Color.WHITE); g2d.translate(rect1.x+(rect1.width/2), rect1.y+(rect1.height/2)); g2d.rotate(Math.toRadians(90)); g2d.draw(rect1); g2d.fill(rect1); } public void actionPerformed(ActionEvent e) { repaint(); } } A: Another way is by using Path2D, with it you can rotate the path only and not the entire graphics object: Rectangle r = new Rectangle(x, y, width, height); Path2D.Double path = new Path2D.Double(); path.append(r, false); AffineTransform t = new AffineTransform(); t.rotate(angle); path.transform(t); g2.draw(path); A: For images you have to use drawImage method of Graphics2D with the relative AffineTransform. For shape you can rotate Graphics2D itself: public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D)g; g2d.setColor(Color.WHITE); Rectangle rect2 = new Rectangle(100, 100, 20, 20); g2d.rotate(Math.toRadians(45)); g2d.draw(rect2); g2d.fill(rect2); } And btw, you should override paintComponent method instead of paint. Citing JComponent's API: Invoked by Swing to draw components. Applications should not invoke paint directly, but should instead use the repaint method to schedule the component for redrawing. This method actually delegates the work of painting to three protected methods: paintComponent, paintBorder, and paintChildren. They're called in the order listed to ensure that children appear on top of component itself. Generally speaking, the component and its children should not paint in the insets area allocated to the border. Subclasses can just override this method, as always. A subclass that just wants to specialize the UI (look and feel) delegate's paint method should just override paintComponent. Remember also than when you perform an affine transformation, like a rotation, the object is implicitly rotated around the axis origin. So if your intent is to rotate it around an arbitrary point, you should before translating it back to the origin, rotate it, and then re-traslating it to the desired point. A: public void draw(Graphics2D g) { Graphics2D gg = (Graphics2D) g.create(); gg.rotate(angle, rect.x + rect.width/2, rect.y + rect.height/2); gg.drawRect(rect.x, rect.y, rect.width, rect.height); gg.dispose(); gg = (Graphics2D) g.create(); ... other stuff } Graphics.create() and Graphics.dispose() allow you to save the current transformation parameters (as well as current font, stroke, paint, etc), and to restore them later. It is the equivalent of glPushMatrix() and glPopMatrix() in OpenGL. You can also apply an inverse rotation once you drew the rectangle to revert the transformation matrix back to its initial state. However, floating point approximations during substractions may lead to a false result. A: The only problem with g2d.rotate is that it doesn't rotate it around a specific point. It will mostly mess up where you want your Image and then force you to move the x and y coordinates of the image. I would not use it,expecially for a game. What you should look into is rotating a point in java.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517688", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: How to call on a object member procedure a nested table attribute? Have this objects and table types: CREATE TYPE Person_typ AS OBJECT ( name CHAR(20), ssn CHAR(12), address VARCHAR2(100) ); CREATE TYPE Person_nt IS TABLE OF Person_typ; CREATE TYPE dept_typ AS OBJECT ( mgr Person_typ, emps Person_nt, MEMBER PROCEDURE getEmp(name IN CHAR(20)), ); CREATE TABLE dept OF dept_typ; How i can get the employer with the function getEmp and argument name ? CREATE TYPE BODY dept_typ AS MEMBER PROCEDURE getEmp(name IN CHAR(20)), BEGIN ????? What i put where ???? END; END; My problem is that i can't make self.emps like I can do with self.mgr ... and i don't know why.... Thanks, Joao A: I suppose you should just select from the emps table: member function getEmp (emp_name in char(20)) return Person_typ IS declare res Person_typ; begin select value (e) into res from self.emps e where e.name = emp_name; return Person_typ; end; there's more A: My guess is that you want something like this SQL> ed Wrote file afiedt.buf 1 CREATE OR REPLACE TYPE dept_typ AS OBJECT 2 ( 3 mgr Person_typ, 4 emps Person_nt, 5 MEMBER FUNCTION getEmp(p_name IN VARCHAR2) 6 RETURN person_typ 7* ); SQL> / Type created. SQL> ed Wrote file afiedt.buf 1 CREATE OR REPLACE TYPE BODY dept_typ AS 2 MEMBER FUNCTION getEmp(p_name IN VARCHAR2) 3 RETURN person_typ 4 AS 5 BEGIN 6 for i in 1 .. self.emps.count() 7 loop 8 if( self.emps(i).name = p_name ) 9 then 10 return self.emps(i); 11 end if; 12 end loop; 13 END; 14* END; SQL> / Type body created. * *If you want getEmp to return something, it should be a function. You could also, I suppose, define it as a procedure with an OUT parameter but that's generally not what you want. *Input and output parameters do not have lengths. You can't declare a parameter as a CHAR(20). You could declare it as a CHAR or as a VARCHAR2 with no length. But there are essentially no cases where a CHAR would be preferred over a VARCHAR2 and employee names are definitely not one of the cases where it's even close. *There is no comma after the declaration of the member function or procedure in either the type spec or the type body. You also need an IS or an AS in the definition of the member function or procedure in the type body. *Since PERSON_NT is a collection, you need to iterate over the collection. Note here that I'm assuming that the collection is dense in this code. You could use the FIRST and NEXT methods on the collection to loop over the elements in a sparse collection as well. If you really want to select from the collection, you'd need to use the TABLE operator. This approach, however, is less efficient and generally more cumbersome than simply iterating over the collection. SQL> ed Wrote file afiedt.buf 1 CREATE OR REPLACE TYPE BODY dept_typ AS 2 MEMBER FUNCTION getEmp(p_name IN VARCHAR2) 3 RETURN person_typ 4 AS 5 BEGIN 6 for i in (select * from table(self.emps)) 7 loop 8 if( i.name = p_name ) 9 then 10 return new person_typ( i.name, i.ssn, i.address ); 11 end if; 12 end loop; 13 END; 14* END; SQL> / Type body created. If you want to add elements to the collection (assuming the collection has previously been initialized) SQL> ed Wrote file afiedt.buf 1 CREATE OR REPLACE TYPE dept_typ AS OBJECT 2 ( 3 mgr Person_typ, 4 emps Person_nt, 5 MEMBER FUNCTION getEmp(p_name IN VARCHAR2) 6 RETURN person_typ, 7 MEMBER PROCEDURE addEmp( p_person IN person_typ ) 8* ); SQL> / Type created. SQL> ed Wrote file afiedt.buf 1 CREATE OR REPLACE TYPE BODY dept_typ AS 2 MEMBER FUNCTION getEmp(p_name IN VARCHAR2) 3 RETURN person_typ 4 AS 5 BEGIN 6 for i in 1 .. self.emps.count() 7 loop 8 if( self.emps(i).name = p_name ) 9 then 10 return self.emps(i); 11 end if; 12 end loop; 13 END; 14 MEMBER PROCEDURE addEmp(p_person IN person_typ) 15 AS 16 BEGIN 17 self.emps.extend(); 18 self.emps(self.emps.count) := p_person; 19 END; 20* END; SQL> / Type body created.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517689", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to set radio button active manually (by code)? I have 2 radio button say r1 and r2.grouped together and made r1 group as true from property. I have made bool variable(vr) and attached with these radio button(DDX). Now from code i wrote vr =1 then updatedata(TRUE). but from ui it is still showing r1 radio button active, instead of r2. how to make radio r2 active by changing vr? A: UpdateData(TRUE) is to update the variables with the controls data. You want to update the controls from the variables, so you must use UpdateData(FALSE). Note: I always add the following defines to stdafx.h so I won't forget: // to use with UpdateData #define TOWINDOW FALSE #define TODATA TRUE and then I just use UpdateData(TOWINDOW) or UpdateData(TODATA).
{ "language": "en", "url": "https://stackoverflow.com/questions/7517694", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using VBA from Access 2007 to search in AutoCAD (dwg) files I have hundreds of DWG, AutoCAD files that I would like search and catalog into an MS Access Database. Basically, I would like to search the DWG's and extract whatever description is in the Title box as well as the Date and bring everything over to Access making it a searchable catalog. For example, I have a file name T-25682.DWG, which is titled Machine Spacer and created 01/20/2010. I would extract that info form the DWG file and insert it into the Access database as such: == ID == == DESCRIPTION == == CREATED ON == == FILENAME == 1 Machine Spacer 01/20/2010 T-25682.dwg How can I approach and solve this problem? Is there an AutoCAD library I can use with Access? How can I search in a DWG file? A: I would avoid VBA altogether, AutoLISP can do the job for with far less pain. Here's how: Create the "data extraction and writing to Access" functionality inside an AutoLISP file. The freely available ADOLisp library will make it a breeze writing to Access, if that fails, or you aren't able to do it you can always just write to a csv file... Once you're able to do that for a single dwg file, create a script (using anything that can copy and open files, AutoLisp works too) to do the following: * *Copy that lisp file into a directory where your dwg files are, naming the file as acaddoc.lsp. *Sequentially open every dwg in the directory. Upon opening, acaddoc.lsp will run and do its stuff. *Delete acaddoc.lsp from that directory (else it will run every time you open a dwg in there). *Repeat for every directory you have dwg files in which you wish to catalog. Notes: * *Make sure that acaddoc.lsp closes the drawing when its done (or makes AutoCAD quit, depending on how you're opening the files). *For this to work, your title blocks need to be reliable, make sure you add some error checking. You can use the script to log any issues to a text file as they find them... AutoLisp is really really easy, for help with learning go to AutoLISP Beginners' Tutorials. For the best place to ask questions and search for code snippets from previous answered questions, see Visual LISP, AutoLISP and General Customization. A: If you have a full version of AutoCAD you can try the Data Extraction Wizard. This works quite well for attributed blocks. If this is no good, the best places to try are the Swamp or the AutoCAD forums or AUGI. VBA is deprecated in the last 3 versions of AutoCAD in favour of the .NET API, FYI +edit+ Have a look at this (free) chapter on AutoCAD external database connectivity.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517695", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: jboss 6.1.0.final gwt and ejb combination this is my first post, so if it isn't understandable, please feel free to ask. I'm trying to develop a gwt-application that uses my own ejb-classes from an external shop-project. My ServiceImpl reaches the ejb, as required, however I'm not able to use Injection as it seems to me. In my ejb-class I call a function to create my test-database with dummy-data. For this (and later on for any requests of course) I wanted to inject an EntityManager. This is done in my Base-Class HomeBase. the problem: The entityManager may not be initialized. I tryed both annotations: @PersistenceUnit(unitName = "sung.app.kylintv.ejb") protected EntityManagerFactory entityManagerFactory; protected EntityManager entityManager = entityManagerFactory.createEntityManager(); as well, as: @PersistenceContext(unitName="sung.app.kylintv.ejb") protected EntityManager entityManager; I'm running jBoss 6.1.0.Final, GWT 2.4 serverside calling my ejb-function. JBoss starts up correctly, not showing any errors. However, when calling the function I get this error-message: Caused by: javax.ejb.EJBException: java.lang.NullPointerException ... Caused by: java.lang.NullPointerException at sung.app.kylintv.HomeBase.<init>(HomeBase.java:28) [:] at sung.app.kylintv.product.ProductHome.<init>(ProductHome.java:35) [:] at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) [:1.6.0_25] at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39) [:1.6.0_25] at By debugging the function I found the entityManager to be NULL. How can I get the injection working? Or am I taking a totally wrong approach on this? For more informations if required: Code: package sung.app.kylintv.gwt.server; import javax.ejb.EJB; import sung.app.kylintv.gwt.client.DatabaseBuilderService; import sung.app.kylintv.product.Product; import sung.app.kylintv.product.ProductHome; import com.google.gwt.user.server.rpc.RemoteServiceServlet; public class DatabaseBuilderServiceImpl extends RemoteServiceServlet implements DatabaseBuilderService { @EJB(mappedName = "sung/app/kylintv/product" ) private transient Product product; @Override public boolean createDefaultDatabaseEntries() { return product.createTestEntry(); } } The initiated class (through interface product) ProductHome: @Stateless(name="Product") @Local(Product.class) public class ProductHome extends HomeBase<ProductEntity> implements Serializable, Product { @EJB protected Option sessionOption; @TransactionAttribute(REQUIRED) public boolean createTestEntry() { try { System.out.println("TEST creating Data BEGIN"); ProductEntity currentProduct = new ProductEntity(); // ++++ fill FIRST product ++++ currentProduct.setName("bo_product_europe_basic_name"); currentProduct.setDescription("bo_product_europe_basic_description"); getEntityManager().persist(currentProduct); **<- HERE THE ERROR OCCURS** ... **For better overview I removed the further object-creation** } catch(Exception e) { //print out an error message and return false System.out.println( e.getCause().getMessage() ); return false; } return true; } } The extended HomeBase: public abstract class HomeBase<T> { @PersistenceUnit(unitName = "sung.app.kylintv.ejb") protected EntityManagerFactory entityManagerFactory; private EntityManager entityManager = entityManagerFactory.createEntityManager(); // @PersistenceContext(unitName = "sung_app_kylintv") // protected EntityManager entityManager; // public void setEntityManager(EntityManager entityManager) { this.entityManager = entityManager; } public EntityManager getEntityManager() { return entityManager; } } A: It looks like you're trying to set an EntityManager from entityManagerFactory, which I don't see initialized anywhere. Perhaps you should check to see if protected EntityManagerFactory entityManagerFactory is null. If so, there's your issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517696", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-5" }
Q: How best to modify and return a C# argument? I need to take a Widget that already has several property values set. I need to change the Widget's name. I'm drawn toward Option 3, but I'm having a hard time articulating why. public void Do(Widget widget) { // 1 widget.Name = "new name"; } public void Do(ref Widget widget) { // 2 widget.Name = "new name"; } public Widget Do(Widget widget) { // 3 widget.Name = "new name"; return widget; } I'd like to play Devil's Advocate with a few questions and gather responses, to help me explain why I'm drawn to Option 3. Option 1 : Why not just modify the Widget that's passed in? You're only "returning" one object. Why not just use the object that's passed in? Option 2 : Why not return void? Why not just communicate in the signature that you'll be using the actual memory pointer to the parameter object itself? Option 3 : Isn't it weird to you that you're returning the same object you're passing in? A: Option 1: Fine. Exactly what I'd use. You can mutate the content of the widget, but not the widget itself. Option 2: No. No. No. You don't modify the reference itself, so you don't need to use ref. If you modified the reference itself (for example widget = new Widget() then out/ref are the correct choices, but in my experience that's rarely necessary. Option 3: Similar to option 1. But can be chained in a fluent style API. Personally I don't like this. I only use that signature if I return a copy and leave the original object untouched. But the most important thing here is how you name the method. The name needs to clearly imply that the original object is mutated. In many situations I'd opt for Option 4: Make the type immutable and return a copy. But with widgets which obviously are entity and not value like, this makes no sense. A: There isn't actually any functional difference between the 3 options. (There ARE differences, just none that are relevant to your question.) Keep it simple - use option 1. A: Option 1: This is the most common approach - you do not need ref if you don't want to modify the reference itself. Make sure that you name your method appropriately so the expectation is that the passed object is indeed modified. Option 2: This is only useful if you want to change the passed reference itself, i.e. create a new Widget instance or set the reference to point to an existing widget (this might be useful if you want to keep overall number of instances low if they all have the same properties, see Flyweight pattern, generally the returned widgets should be immutable in this case though and you would use a factory instead). In your case this does not seem appropriate. Option 3: This allows for a fluent "builder" approach - also has its benefits, i.e chaining of changes to the Widget which some people consider more expressive and self-documenting. Also see Fluent interface A: I think Option 1 and Option 3 are both viable options. Option 3 has the benefit of being self-documenting in that it implies that you are modifying Widget in the method. I think the worst option is Option 2. The ref keyword to me implies that you are modifying the reference of the object, which you are most certainly not doing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517697", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Prolog meta-predicates: applying a predicate to lists, passing a constant Assume that you want a predicate that replaces Number1 with Number2 in a list. Of course it is trivial to write a recursive function for that, like: replace(_,_,[],[]). replace(N1,N2,[N1|T], [N2|NT]):- replace(N1,N2,T,NT). replace(N1,N2,[H|T],[H|NT]):- replace(N1,N2,T,NT). My question is if there is a way to do that with maplist/x (or similar meta-predicates). One might use global variables to do that, like: replace(N1,N2,L1,L2):- nb_setval(numbers,[N1,N2]), maplist(replace_in,L1,L2). replace_in(N1,N2):- nb_getval(numbers,[N1,N2]). replace_in(X,X). Another idea is to create a list of the same numbers List_of_N1 and List_of_N2 and pass them to maplist/4. None of them look attractive to me, any ideas? A: As an aside: With your given definition, consider for example the apparently unintended second solution in: ?- replace(1, 4, [1,2,3], Ls). Ls = [4, 2, 3] ; Ls = [1, 2, 3] ; false. As to the actual question, consider: replace(A, B, X, Y) :- ( X == A -> Y = B ; Y = X ). Example query: ?- maplist(replace(1,4), [1,2,3], Ls). Ls = [4, 2, 3]. For logical-purity, I recommend a truly relational version which can be used in all directions: replacement(A, B, A, B). replacement(A, _, X, X) :- dif(A, X). Example: ?- maplist(replacement(a,b), [X], Rs). Rs = [b], X = a ; Rs = [X], dif(X, a). A: How about this: replace(N1,N2,L1,L2):- maplist(replace_in,[N1-N2-T|T], L1,L2). replace_in(N1-N2-T, X, Y):- (X=N1 -> Y=N2 ; Y=X), (T=[N1-N2-L|L] ; T=[]).
{ "language": "en", "url": "https://stackoverflow.com/questions/7517698", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to simulate mouse clicks in QML? I'm trying to send a QMouseEvent to the QML objects being currently displayed. The QApplication::sendEvent() always returns false meaning that my event did not get handled; but I don't see why. Maybe I'm sending the event to the wrong object? Where should I send it to? I also played around with QGraphicsSceneMouseEvent instead of QMouseEvent but had no luck either. I tried stepping through the event code with the debugger but it is too complex for me to see why it's not working. Background I'm working on a piece of software that will be controlled via a simple touch screen. I get the touch events via ethernet and I want to synthesize mouse click events from them. This way the software will be controlled on the target device in the same way as on a developer PC. Update * *As noted by fejd, the click code was executed before QApplication::Exec(), so I moved it into a timer handler that will be triggered while exec() is running. *Added Windows-specific code that works as expected. *Added some more attempts in Qt none of which works no matter whether sendEvent() returns true or false. So far I have this: main.cpp #include <QtGui/QApplication> #include "qmlapplicationviewer.h" #include "clicksimulator.h" #include <QTimer> int main(int argc, char *argv[]) { QApplication app(argc, argv); QmlApplicationViewer viewer; viewer.setOrientation(QmlApplicationViewer::ScreenOrientationAuto); viewer.setMainQmlFile(QLatin1String("qml/qmlClickSimulator/main.qml")); viewer.showMaximized(); ClickSimulator sim(&viewer); QTimer timer; sim.connect(&timer, SIGNAL(timeout()), SLOT(click())); timer.start(100); return app.exec(); } clicksimulator.h #ifndef CLICKSIMULATOR_H #define CLICKSIMULATOR_H #include <QObject> class QmlApplicationViewer; class ClickSimulator : public QObject { Q_OBJECT QmlApplicationViewer* m_viewer; public: explicit ClickSimulator(QmlApplicationViewer* viewer, QObject *parent = 0); public slots: void click(); }; #endif // CLICKSIMULATOR_H clicksimulator.cpp #include "clicksimulator.h" #include "qmlapplicationviewer.h" #include <QMouseEvent> #include <QDebug> #include <QGraphicsSceneMouseEvent> #include <QApplication> #include <QGraphicsScene> #include <QTest> #define _WIN32_WINNT 0x0501 #define WINVER 0x0501 #include "Windows.h" ClickSimulator::ClickSimulator(QmlApplicationViewer* viewer, QObject *parent) : QObject(parent) , m_viewer(viewer) { } void ClickSimulator::click() { if (NULL != m_viewer) { const int x = qrand() % 500 + 100, y = qrand() % 500 + 100; { QMouseEvent pressEvent(QEvent::MouseButtonPress, QPoint(x, y), Qt::LeftButton, Qt::LeftButton, Qt::NoModifier); // QMouseEvent pressEvent( // QEvent::MouseButtonPress, // QPoint(x, y), // Qt::LeftButton, Qt::LeftButton, Qt::NoModifier); const bool isSent = QApplication::sendEvent(m_viewer->scene(), &pressEvent); qDebug() << "'Press' at (" << x << "," << y << ") successful? " << isSent; } { QGraphicsSceneMouseEvent pressEvent(QEvent::GraphicsSceneMousePress); pressEvent.setScenePos(QPointF(x, y)); pressEvent.setButton(Qt::LeftButton); pressEvent.setButtons(Qt::LeftButton); QGraphicsItem* item = m_viewer->itemAt(x, y); const bool isSent = m_viewer->scene()->sendEvent(item, &pressEvent); //const bool isSent = QApplication::sendEvent(m_viewer->scene(), &pressEvent); qDebug() << "'Press' at (" << x << "," << y << ") successful? " << isSent; } // This platform specific code works... { const double fScreenWidth = ::GetSystemMetrics( SM_CXSCREEN )-1; const double fScreenHeight = ::GetSystemMetrics( SM_CYSCREEN )-1; const double fx = x*(65535.0f/fScreenWidth); const double fy = y*(65535.0f/fScreenHeight); INPUT inp[3]; inp[0].type = INPUT_MOUSE; MOUSEINPUT & mi = inp[0].mi; mi.dx = fx; mi.dy = fy; mi.mouseData = 0; mi.dwFlags = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE; mi.time = 0; mi.dwExtraInfo = 0; inp[1] = inp[0]; inp[1].mi.dwFlags = MOUSEEVENTF_LEFTDOWN; inp[2] = inp[0]; inp[2].mi.dwFlags = MOUSEEVENTF_LEFTUP; SendInput(3, inp, sizeof(INPUT)); } } } main.qml import QtQuick 1.0 Rectangle { width: 360 height: 360 Text { id: text1 text: qsTr("This text is placed at the click coordinates") } MouseArea { id: mousearea1 anchors.fill: parent onClicked: { console.log("click at " + mouse.x + ", " + mouse.y); text1.pos.x = mouse.x; text1.pos.y = mouse.y; } } } output 'Press' at ( 147 , 244 ) successful? false 'Press' at ( 147 , 244 ) successful? true A: Since you send the event before app.exec(), I don't think the main event loop has been started . You could try postEvent instead, though that might fail as well if exec() clears the event queue before it starts. In that case, perhaps you can post it somewhere after exec()? Update: Got it working now by looking at the QDeclarativeMouseArea autotests. What was missing was the release event. This worked for me: QGraphicsSceneMouseEvent pressEvent(QEvent::GraphicsSceneMousePress); pressEvent.setScenePos(QPointF(x, y)); pressEvent.setButton(Qt::LeftButton); pressEvent.setButtons(Qt::LeftButton); QApplication::sendEvent(m_viewer->scene(), &pressEvent); QGraphicsSceneMouseEvent releaseEvent(QEvent::GraphicsSceneMouseRelease); releaseEvent.setScenePos(QPointF(x, y)); releaseEvent.setButton(Qt::LeftButton); releaseEvent.setButtons(Qt::LeftButton); QApplication::sendEvent(m_viewer->scene(), &releaseEvent); What was a bit odd was that onPressed in the QML file did not get called after the press event - only after the release event was sent as well. A: The accepted answer works, but there is a better way. Just use QGraphicScene's bool sendEvent(QGraphicsItem* item, QEvent* event) function. If you know which item to send the event to.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517700", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Windows batch script copy file last modified I'm trying to write a quick batch script to look at the last modified date of one file and compare it to the last modified date of a few others, and if it's greater than those other lastmods, it copies the files to those directories. This is what I have so far: @echo off for %%a in ([srcFile]) do set lastmodSrc=%%~ta echo lastmodSrc for %%a in ([dstFile1]) do set lastmodDst1=%%~ta for %%a in ([dstFile2]) do set lastmodDst2=%%~ta for %%a in ([dstFile3]) do set lastmodDst3=%%~ta for %%a in ([dstFile4]) do set lastmodDst4=%%~ta if lastmodSrc GTR lastmodDst1 xcopy [srcFile] [dstDir1] /-y if lastmodSrc GTR lastmodDst2 xcopy [srcFile] [dstDir2] /-y if lastmodSrc GTR lastmodDst3 xcopy [srcFile] [dstDir3] /-y if lastmodSrc GTR lastmodDst4 xcopy [srcFile] [dstDir4] /-y pause The square brackets are full path names. What it's doing right now is saving lastmodSrc and lastmodDst as just the strings (at least that's what it seems like it's what it's doing), and so it's not actually checking the mod dates. I'm woefully inadequate at batch scripting in Windows, figured someone here might be able to help. Thanks in advance! A: Another approach that might be simpler (assuming I understand the goal) would be to use the /d option on xcopy. If that is given (without a date), it will copy the file only if the source is newer: xcopy /d srcfile dstfile
{ "language": "en", "url": "https://stackoverflow.com/questions/7517703", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Java: split() returns [Ljava.lang.String;@186d4c1], why? And i have no idea why! I bascially have a STRING (yes, not an array), that has the following contents: [something, something else, somoething, trallala, something] And i want to turn it into a String[]. So first off i substring() off the first and the last character to get rid of the brackets []. Then i use the split() function to split by comma. I tried using both "\|" and "," and "\," with the same results. This is what i get: [Ljava.lang.String;@186d4c1 Here's the code for it. I made it into a one-liner: String[] urlArr = ((matcher.group(3).toString()).substring(1, (matcher.group(3).length()-1))).split(","); As you can see the first part is (matcher.group(3).toString()), and it DOES return a valid string (like the example i posted above). So i don't get why it's not working. Any ideas? EDIT: I clarified the code a bit: String arrString = matcher.group(3).toString(); int length = arrString.length(); String[] urlArr = (arrString.substring(1, length-1)).split(","); System.out.println(urlArr); A: The output [Ljava.lang.String;@186d4c1 is the way java prints a string array (or any array) by default (when converted to a string). You may use Arrays.toString(urlArr) to get a more readable version. A: You are getting a valid array of Strings, but trying to print it directly does not do what you would expect it to do. Try e.g. System.out.println(Arrays.asList(urlArr)); Update If you want to process the parsed tokens one by one, you can simply iterate through the array, e.g. for (String url : urlArr) { // Do something with the URL, e.g. print it separately System.out.println("Found URL " + url); } A: When you do toString on an Array, you just get the internal representation. Not that useful. Try Arrays.toString(what comes back from split) for something more readable.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517704", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Passing array in JQuery Script Been working on this dumb problem for two days now. If you can help I would sure appreciate it! So my html goes like this: <a class='selected' option ='2' category='1' price='1750.00'>Round Corners</a> <a class='selected' option ='3' category='1' price='2200.00'>Chamfer Corners</a> And then my script is: $('#save').click(function(){ var passOptions = new Array(); var i=0; $('.selected').each(function(){ passOptions[i] = $(this).attr('option'); i++; }); console.log(passOptions); $.ajax({ type: "POST", url: "processsaveconfig.php?configid=<? echo $configid; ?>", data: { passOptionsArray : passOptions }, success: function() { $('#pricediv').html(data); } }); }); My php page goes: $passopts = $_REQUEST['passOptionsArray']; mysql_connect($serverpath, $dbusr, $dbpass) or die(mysql_error()); mysql_select_db($dbname) or die(mysql_error()); mysql_query("DELETE FROM se_config_opt_link WHERE se_config_opt_link.f_config_id = '$configid'"); foreach ($_POST['passOptions'] as $opts){ mysql_query("INSERT INTO se_config_opt_link (f_config_id, f_opt_id) VALUES ('$configid', '$opts')"); }; In Firebug in the Console tab I get: ["1", "4", "7"] But in the Response tab it reads: Warning: Invalid argument supplied for foreach() in /home/users/c/companion/public_html/dynamic/builder_app/processsaveconfig.php on line 17 I'm stuck. If you can help I would really be grateful. A: It seems to me you're looking for this: $('#save').click(function(){ var passOptions = []; $('.selected').each(function(){ passOptions.push($(this).attr('option')); }); console.log(passOptions); in your PHP, use something like this: $myArray = $_POST['passOptionsArray']; if (is_array($myArray)({ ... } I expect that will make the difference. A: Shouldnt the foreach ($_POST['passOptions'] as $opts){... be more like foreach ($_POST['passOptionsArray'] as $opts){...
{ "language": "en", "url": "https://stackoverflow.com/questions/7517706", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to document fields in a record in clojure? For example: (defrecord Contract [^{:doc "primary identifiers..."} contract-id]) But this doesn't seem to work: (doc Contract) clojure.lang.Cons cannot be cast to clojure.lang.Symbol [Thrown class java.lang.ClassCastException] Maybe you can't document record fields? A: defrecord compiles a new class and uses these names as the fields of that class. Unfortunatly classes predate clojure and leave no room for metadata :( The class will have the (immutable) fields named by fields, which can have type hints.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517708", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How to connect people to random partners in chat application? I'm developing an app to be hosted on GAE.Basically my app needs to connect people randomly. I did similar app before where i assigned unique id to each user.Once the user enter the app his ID will be inserted into static synchronized LinkedHashSet(which acts like global datastore for app).Similarly second user enters synchronized LinkedHashSet,If he finds the ID other than his ID then they are connected.The Second user removes their ID's from LinkedHashSet and Inserts them into Mysql DataBase as pairs.Note that access to LinkedHashSet is synchronized. Now i wanted to design a similar app in cloud environment like GAE.But in GAE static variables are not global since the distributed nature of app engine.How to write similar code in cloud environment? A: There are multiple approaches to this problem. You can very well use a combination of Channel API, DataStore API, Memcache API for providing a scalable real time chat room application. Here is a good article on creating multiuser chatroom application - http://codecontrol.blogspot.com/2010/12/multiuser-chatroom-with-app-engine.html, http://code.google.com/p/channel-tac-toe/ You will have to use datastore for storing the LinkedHashSet and further cache it in memcache for faster access.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517711", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Pass Image to other activity I want to load image from web, then decode it by the BitmapFactory.decode() method. now I have image in bitmap. i want it to load on the imageview which is View of the another activity So how can i load the image on the other activity A: Bitmap appears to inherit 'Parcelable'. This implies you should be able to putExtra() and then getParcelableExtra() A: You could use the application context to hold the bitmap. Way to use app context. Extend the application class and add a attribute of type Bitmap. So in your activity you can access the application context and get the bitmap. As the application context is a singleton it will be the same instance in every activity. MyApplication appContext = (MyApplication) getApplicationContext(); appContext.bitmap = YOUR BITMAP; In any other activity you can access that bitmap the same way. MyApplication appContext = (MyApplication) getApplicationContext(); Now the bitmap is in the appContext object. You also need to add android:name=".MyApplication" to application tag in the manifest file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7517713", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }