text
stringlengths
8
267k
meta
dict
Q: Wordpress: WP_Query search criteria on 'post_name' I'm using WP_Query (pretty standard). It all works great. However, I have a particular modification to make, where, if the user enters the specific post name in the URL, the search will return only the post that matches that post_name value. See my code below with a comment about the particular line not working. <?php $getPeople = array( 'post_type' => 'person', 'posts_per_page' => -1, // I want this below to only return me the post with this specific value. // This doesn't error, but doesn't work either. // I know it seems counter-productive to a 'search' but this particular case requires it. // This has a hard-coded value at the moment. 'post_name' => 'rebecca-atkinson', 'orderby' => 'meta_value', 'meta_key' => 'last-name', 'order' => 'ASC', 'meta_query' => array( array( 'key' => 'gender', 'value' => $theGender, ) ), 'tax_query' => array( 'relation' => 'OR', array( 'taxonomy' => 'accent', 'field' => 'slug', 'terms' => $theAccent, 'operator' => 'IN', ), array( 'taxonomy' => 'style', 'field' => 'slug', 'terms' => $theStyle, 'operator' => 'IN', ), array( 'taxonomy' => 'age', 'field' => 'slug', 'terms' => $theAge, 'operator' => 'IN', ), ) ); $myposts = new WP_Query($getPeople); ?> Your help would be greatly appreciated. If I could just see how to search on this specific 'slug' then that would be great. Many thanks, Michael. A: In addition to my answer in the comments above, I thought I'd post it as an official answer too: I have to use 'name' and NOT 'post_name'. For example: 'name' => 'rebecca-atkinson' Hope this helps someone in future. A: Instead of 'post_name' => 'rebecca-atkinson', use: 'name' => 'rebecca-atkinson',
{ "language": "en", "url": "https://stackoverflow.com/questions/7600239", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Using PHP, how can I make a cookie expire after the browser is closed? Using PHP, how can I make a cookie expire after the browser is closed? A: Just don't set an expiry time. That will make it a session cookie. This is mentioned in the documentation for the expire argument to setcookie: If set to 0, or omitted, the cookie will expire at the end of the session (when the browser closes).
{ "language": "en", "url": "https://stackoverflow.com/questions/7600248", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Custom JSP tag does not render dynamic body content I have created a new JSP tag (in a Struts 1.2.9/Java 5/Tomcat 5.5 web application), which renders content within the tag body, when the logged-in user has one of the given roles. <?xml version="1.0" encoding="UTF-8"?> <%@ attribute name="userRoles" rtexprvalue="false" required="true" description="Comma-separated list of user role names, against which the logged-in user's roles are tested." %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <jsp:directive.tag description="Evaluates the nested body content if the logged-in user has one of the roles given in the userRoles attribute." /> <jsp:directive.tag body-content="tagdependent" /> <c:if test="${sessionScope.userData ne null}"> <jsp:doBody var="bodyContent" scope="page"/> <jsp:scriptlet> String userRoles = (String) jspContext.getAttribute("userRoles"); com.initech.core.db.model.UserData userData = (com.initech.core.db.model.UserData) session.getAttribute("userData"); if(com.initech.web.struts.action.UserUtils.hasOneOfRolesInCommaSeparatedList(userData, userRoles)){ String bodyContent = (String) jspContext.getAttribute("bodyContent"); out.write(bodyContent); } </jsp:scriptlet> </c:if> Example of a file, where the custom tag is used: <?xml version="1.0" encoding="UTF-8"?> <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" xmlns:tiles="http://jakarta.apache.org/struts/tags-tiles" xmlns:initech-user="urn:jsptagdir:/WEB-INF/tags/initech-user/"> <html:xhtml /> <initech-user:userHasRole userRoles="Admin,TPS Manager,"> abcde <tiles:insert name="tiles.components.deletebutton"> <tiles:put name="deleteClass" value="build"/> <tiles:put name="deleteId" value="${sessionScope.buildForm.id}"/> </tiles:insert> </initech-user:userHasRole> </jsp:root> The tag works partially, in the sense that all "normal" content within the tag is rendered (html tags, text). In the example above the text "abcde" is visible on the JSP page, but the content inserted with the nested tiles tags is not visible. To clarify, the following part is not rendered correctly: <tiles:insert name="tiles.components.deletebutton"> <tiles:put name="deleteClass" value="build"/> <tiles:put name="deleteId" value="${sessionScope.buildForm.id}"/> </tiles:insert> When I look at the HTML source, I see that the content is rendered directly to the JSP page "as is" (i.e. written to the page as if it were normal HTML content), but of course I want the tiles tags to be evaluated and the output of the tags to be written within my own tag. This does apparently not apply only to tiles tags, but also to other dynamic content. Is it possible to implement a custom tag so that also the content inserted by the tiles tag-library is rendered? A: Problem solved by changing the tag directive "body-content" followingly: <jsp:directive.tag body-content="scriptless" /> A: In tomcat 6.x jsp 2.1 you must use: <%@tag body-content="scriptless" %>
{ "language": "en", "url": "https://stackoverflow.com/questions/7600251", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: asp menu control not looking properly in view page source from browser I have a problem with asp menu control. I want to display my menu orientation as horizontal. It is looking fine when i debug, but when i see the viewsource of my page it is displaying vertically and my sub items also displaying. See the below two images how my menu is displaying when i debug and after view source from browser also why it is showing skipnavigation links when i view source? I dont have nothing in my page except the menu control. A: Did you try to set the ShowStartingNode of your SiteMapDataSource to false?
{ "language": "en", "url": "https://stackoverflow.com/questions/7600253", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I control column size for enums? This is with EclipseLink via JPA, where I let it create the tables for me. The back end data base is Derby for development mode, and I expect to use MySQL or something else for deployment. In my entity I have an enum: @Entity public class Thing implements Serializable { public enum Choice { Able, Baker, Charlie, Delta } @Column(precision = 1) private Choice choiceValue; // etc } The enum ordinal only needs one digit, but when the table gets created it allocates 10 digits for it. So a million records will waste 9 Megabytes. The "precision = 1" term is ignored. Is there a way to cause it to use just one byte to encode the enum? A: Setting scale or precision for Integer column where enum is mapped in Derby & EclipseLink does not help. It does nothing, you will end up with INTEGER anyway. You can have more control with following. @Column(columnDefinition = "SMALLINT") //smallint= 2 bytes or //@Column(columnDefinition = "NUMERIC(1)") // private Choice choiceValue; It had worked for me, but basically Java type for NUMERIC is BigDecimal and for SMALLINT short, maybe that can produce problems in some cases. For example native queries will return BigDecimal for choiceValue-column. How much storage is needed depends bit about database provider, some older MySQL stored character per digit, now it seems to be quite fine tuned: http://dev.mysql.com/doc/refman/5.0/en/precision-math-decimal-changes.html I don't know how it is exactly in Derby, but I would assume it not taking more than byte.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600255", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Spring Import Can't See Resources I'm using Spring to handle my dependency injection and I am currently writing a jar that makes use of a homegrown logging-1.0.jar that I also made some time ago. I am writing this inside Eclipse, which may be important. That logging-1.0.jar has a critical config file in it called logging-base.xml where all sorts of environmental properties get set so that my logger works correctly. My new jar is compiling/building in Ant fine, but at runtime is throwing an exception stating: Exception in thread "main" org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Failed to import bean definitions from URL location [classpath:logging-base.xml] Offending resource: class path resource [spring/client-config.xml]; nested exception is org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://camel.apache.org/schema/spring] Offending resource: class path resource [logging-base.xml] So it seems that Spring cannot find my logging-base.xml file as its not "in the classpath". In my project I have a lib/ directory where all of my dependent jars are stored. When I copy a new jar into this directory, I just right-click it and go Build Path >> Add to Build Path and Eclipse makes a reference of that jar available to the runtime. Of all the jars under my lib/ directory, logger-1.0.jar has a distinct icon next to its name in the package explorer. Its icon has a little tiny question-mark ("?") in it. So I'm guessing that, somehow, my logging jar isn't configured correctly, and as a result, isn't adding its logging-base.xml file to the classpath. As such, at runtime, Spring can't find it. But that's where my knowledge of Eclipse and Spring grinds to a halt. Any ideas? A: I think the issue might be with spring handlers, You might have defined this name space http://camel.apache.org/schema/spring in your client-config.xml, Spring usually has name space handlers defined for every name space that is defined in the application context. These handlers are defined in a file called spring.handlers and are included in the respective jars in this case (camel-spring-X.jar). A: You might want to add xerces.jar and in jre6\lib\ext directory, Just try this out.. coz it helped me solve this problem !
{ "language": "en", "url": "https://stackoverflow.com/questions/7600256", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Alternatives to NOP for shellcode nop sleds Does anyone know of any online source that provides instruction alternatives to a NOP opcode ? Like 'xchg ax, ax' and the likes. I'm pretty sure that there is also a tool for it, can someone point me to that direction please ? A: Some shellcode engines contain nop sled generators, if that is what you're looking for. Though there are an infinite variety of nop-equivalents of various lengths, so an exhaustive listing is impractical. For instance, push eax; pop eax is effectively a nop. (assuming a valid esp, etc, etc) Or inc eax; dec eax (assuming no overflow or you test then reset the overflow flag). A: This page has a nice list of NOP alternatives with increasing encoding lengths: http://www.asmpedia.org/index.php?title=NOP A: An alternative to NOP that's useless for nop sleds, but useful for performance: What methods can be used to efficiently extend instruction length on modern x86? (e.g. add extra prefixes to make instructions longer). Normally your exploit payload doesn't care about register values (other than the stack pointer), so you can freely destroy them with things like inc eax (single-byte in 32-bit code). There are lots of single-byte instructions that only modify registers and won't fault. e.g. cld/std, stc/clc/cmc, cwde, cdq are all single-byte. Again in 32-bit code, even BCD instructions like AAA or DAA are usable, but those will stick out like a sore thumb because compilers never use them. (Compilers do in practice use cdq and maybe cwde, but typically not cld or std.) Also the other xchg-with-eax one-byte 0x91..7 instructions, other than 0x90 nop which uses the same encoding that xchg eax,eax would have, and could in 32-bit mode. (But note that xchg eax,eax in 64-bit mode isn't a NOP; it has to use the other encoding so it can truncate RAX to EAX.) With any multi-byte instruction like mov eax,eax, make sure to check how it decodes if execution starts at something other than the first byte. The whole point of a sled is that execution has to land somewhere inside the buffer but you don't know where. You can use optional prefixes to make multi-byte instructions that still decode ok if execution starts after the prefix. cbw is 0x66 cwde (operand-size prefix). Or REX prefixes (0x40..4f), so xchg rax,rcx for example. rep prefixes are typically ignored safely on instructions they don't apply to, but may run differently on future CPUs. (e.g. rep nop used to just be NOP, but now it's pause. rep bsr is now lzcnt, which produces a different result.) This is fine for shellcode, you're trying to exploit one system now, not be future-proof for future CPUs. If you know the target buffer alignment, then you control (via the low bits of the instruction pointer) which possible offsets you can jump to. If the buffer is 4-byte aligned (or more specifically that your payload will end up a 4-byte aligned location), then only every 4th byte needs to be a valid starting point for decoding, so you can use pairs of 2-byte instructions like xor eax, ebx / add ecx, edx. 4-byte instructions include addss xmm0, xmm1 and other SSE1/SSE2 instructions. Unless the code you're exploiting is running in kernel mode with SSE disabled, you can normally assume that whatever machine you're exploiting has SSE1. You could even use a 5-byte instruction like mov eax, 0x90345612 starting at a 4-byte aligned address. Note that the last byte of the little-endian immediate is 0x90 nop, so it's ok if decoding starts there. My understanding is that techniques like this are widely used to work around intrusion-detection systems / virus scanners that find long strings of 0x90 suspicious. (And/or because 0x90 is not printable ASCII, and not valid UTF-8). A: The intel optimization manual and the instruction manuals for intel and AMD should have listing of all the no op equivalent functions. It should be noted that most of them are multi byte no ops, to be used for aligning branch and code cache targets etc. A: From the internet archive of the dead link in the top answer. 90 nop 6690 xchg ax,ax ; 66: switch to 16-bit operand 90: opcode 0f1f00 nop dword ptr [eax] ; 0f1f: 2-byte opcode 00: mod=00 reg=000 rm=000 [EAX] 0f1f4000 nop dword ptr [eax] ; 0f1f: 2-byte opcode 40: mod=01 reg=000 rm=000 [EAX+0x00] 0f1f440000 nop dword ptr [eax+eax] ; 0f1f: 2-byte opcode 44: mod=01 reg=000 rm=100 SIB + 0x00 660f1f440000 nop word ptr [eax+eax] ; 66: switch to 16-bit operand 0f1f: 2-byte opcode 44: mod=01 reg=000 rm=100 SIB + 0x00 0f1f8000000000 nop dword ptr [eax] ; 0f1f: 2-byte opcode 80: mod=10 reg=000 rm=000 [EAX+0x00000000] A: just think through the different operations that dont change anything (other than flags). add zero to a register, or the register with itself and the register with itself, move the register to itself. subtract 0, or with zero, and with ~0. A bit test type instruction, usually an and but the destination is not modified.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600260", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Control Android TextView visibility run time programmatically In my Java Android application, in run time according to a condition I need to setvisible false in a TextView. How to do it run time programmatically? A: You're looking for the setVisibility method in View. textView.setVisibility(View.GONE); textView.setVisibility(View.INVISIBLE); It doesn't take a boolean because you can set it to either Invisible or Gone. If it's Gone, it will not take up any "space" in the layout.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Why are my requests from urllib2 delayed with Apache2? I'm dealing with two internal web servers, one running Apache2 on Ubuntu Server 10.04, and the other IIS on Windows Server 2008. When I hit either of the root URLs from a web browser with a cleared cache, calling the server by IP address, both pop up with no delay. I also see no delays browsing sites on either server. However, when I call the same addresses using urllib2 in Python, each request to the Apache2 server is delayed by 4.5 to 5 seconds. The IIS server responds in less than 0.02. Here is a script I ran to verify the problem. I set the User-Agent in case it makes a difference, but it doesn't appear to: import urllib2 from time import time apache_server = 'http://192.168.1.101/' iis_server = 'http://192.168.1.102/' headers = {'User-Agent' : "Mozilla/5.0 (X11; U; Linux i586; de; rv:5.0) Gecko/20100101 Firefox/5.0",} print('Contacting Apache2 server...') request = urllib2.Request(url=apache_server, headers=headers) start = time() response = urllib2.urlopen(request).read() elapsed = time() - start print('Elapsed time: {0}'.format(elapsed)) print('Contacting IIS server...') request = urllib2.Request(url=iis_server, headers=headers) start = time() response = urllib2.urlopen(request).read() elapsed = time() - start print('Elapsed time: {0}'.format(elapsed)) Results: >python urltest.py Contacting Apache2 server... Elapsed time: 4.55500006676 Contacting IIS server... Elapsed time: 0.0159997940063 What difference is there between a browser request and my urllib2 request that would explain this delay? I've seen similar problems with SSH caused by reverse DNS lookup, but I have HostnameLookups Off in my Apache2 config. I don't know if anything else could be triggering a lookup. Update: I followed the exchange with Wireshark, and found three failed NBNS queries going from my machine to the Apache2 server before they finally start talking. This accounted for the lost time. I tried adding an entry in hosts for the web server, which eliminated the delay. I'm not adding this as an answer because I still don't know why the lookup attempt is happening, or why I don't see the same behavior from the web browser. I just have a workaround for whatever mistake I'm making. A: The lookup is happening because that's what Windows does. It's always going to check NetBIOS before anything else. Further reading: * *Microsoft TCP/IP Host Name Resolution Order *NetBIOS over TCP/IP Name Resolution and WINS
{ "language": "en", "url": "https://stackoverflow.com/questions/7600267", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: submit form in spring MVC by clicking on Link Is there any way to submit the form in spring MVC by clicking on Link or do I need to use the javascript submit method Thanks A: Use JQuery on submit function as the event on url click: $('#formName').submit();
{ "language": "en", "url": "https://stackoverflow.com/questions/7600269", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Break activity classes into multiple files This is the main activity I am trying to move like classes to a new file Once I do, I am not able to successfully call the class The following code generates a null pointer, though the pointer is not null I cannot simply change the savedTrainInfo class to static because then the file routines will not work. There must be a simple solution I need to keep my classes separate for clarity. import mp.trains.conductor.savedTrainInfo; public class trains extends Activity { private savedTrainInfo msavedTrainInfo; protected static Context context; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); trains.context=getApplicationContext(); msavedTrainInfo=new savedTrainInfo(); msavedTrainInfo.getTrainAttributes(); } } new file many functions here; mainly file I/O These all work fine if there are located in the main activity trains You are correct. The error seems to be in if (readStartupFile(trainAttributes)==false) public class savedTrainInfo extends trains { public void getTrainAttributes() { trainAttributes=new String [10]; if (readStartupFile(trainAttributes)==false) { fileLine=0; } else { try { fileLine = Integer.parseInt(trainAttributes[0].toString()); } catch(NumberFormatException nfe) { System.out.println("Could not parse " + nfe); } } } public boolean readStartupFile(String objects[]) { try { // InputStream fHandle = openFileInput("startupTrains.txt"); InputStream fHandle = trains.context.openFileInput("startupTrains.txt"); if (fHandle != null) { // prepare the file for reading InputStreamReader inputreader = new InputStreamReader(fHandle); BufferedReader buffreader = new BufferedReader(inputreader); String line; line = buffreader.readLine(); if (line == null) { fHandle.close(); return false; } else { String[] item = (line).split(","); objects[0]=item[0].toString(); fHandle.close(); } return true; } else { return false; } } catch (FileNotFoundException e2) { return false; } catch (IOException e) { e.printStackTrace(); return false; } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7600273", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Java: How can we create callback function when "function pointer is prohibited"? Possible Duplicate: What's the nearest substitute for a function pointer in Java? Callback functions in Java I would like to ask some concept of the term callback. What is the main purpose of using callback? Is it only for doing some async function? from the wiki, i can't get what does actually means. This part of code is copied from wiki- callback void PrintTwoNumbers(int (*numberSource)(void)) { printf("%d and %d\n", numberSource(), numberSource()); } /* One possible callback. */ int overNineThousand(void) { return (rand() % 1000) + 9000; } /* Here we call PrintTwoNumbers() with three different callbacks. */ int main(void) { PrintTwoNumbers(overNineThousand); } from the wiki, it said the we need to pass a function pointer as arguments to other functions in order to do a callback. But in java, there is no way to pass-by-references when we call a function, can we make a callback function in Java just like above code? Thanks A: Up until now, Java has used interfaces and (sometimes anonymous) implementations of said interfaces to behave as callbacks. For simple callbacks, you can use java.util.Runnable or java.util.concurrent.Callable instead of defining your own interfaces. Upcoming versions of Java will add better support for doing elegant callbacks, see this. A: You can create an anonymous class instance implemening interface with only one method e.g. Callable: Callable<Integer> function = new Callable<Integer>() { Integer call() { return ...; } } And then in the code that uses a callback just call it like that: int result = function.call(); A: Function pointers are what you use if you do not have an OO language. C++ inherited them from C. Instead, take a look at the Strategy design pattern. A: not really the only thing you can pass is object references but with the right interface... return new CallBack(){ public void call(){ //... } } generics for ret value and args will be a nice expansion
{ "language": "en", "url": "https://stackoverflow.com/questions/7600276", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it possible to change PRIVATE data memebers of a CLASS illigaly? Possible Duplicate: Is it possible to access private members of a class? Is it possible to change PRIVATE data memebers of a CLASS without Member function or Friend function,by creating object of that class and accessing address of that created object,is it possible to some how modify PRIVATE data members using such POINTERS if we know the address of that class??? A: Assuming you know the in-memory layout of the class fields, it is indeed possible to change its private members using something like *((FieldType*)((char*)&object + fieldOffset)) = someValue;. You shouldn't do this. It's criminal. A: The language is not there to police you but rather to keep you from making mistakes. You can do a set of different things to gain access to the private fields, but at the end of the day, none of them is a good idea on the premise that if the class is yours, you can provide access in a sensible way, and if it is not yours, all private members are implementation details that can change from one version to another and there are most probably invariants of the class that you might or not know and could break if you modify those members.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600277", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a way of limiting the depth of the trace generated by xdebug? The question says it all, really. I am trying to figure out why a php app is misbehaving, but the sheer amount of data thrown at me by xdebug makes it hard to understand the flow. If I could set the depth of the trace such that any call more than x levels deep was skipped, then it would be easier to understand what was happening. Any ideas how to make xdebug do this, or is there an alternative tool I can use? A: Xdebug's function/execution tracing to file does currently not support this, and Xdebug's stacktraces always also show the whole stack I've just added a feature request to the issue tracker for it: http://bugs.xdebug.org/view.php?id=722 Derick A: You can tell Xdebug where to start and stop the function tracing by calling functions xdebug_start_trace() and xdebug_stop_trace() in the code. With Xdebug version 2.4 or higher, you can also limit Xdebug to only trace execution of some functions by calling function xdebug_start_function_monitor( array $list_of_functions_to_monitor ). The array contains the list of functions you want to trace.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600284", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: nUnit Exception on a 64 bit Machine I have an MVC 3.0 app. My testing framework is nUnit 2.4.8.0. I started this code on a 32 bit machine, and recently started using a 64 bit machine. I just as recently upgraded the project to .NET 4.0. My application runs fine - I am able to hydrate my objects from the database appropriately. The issue is when I run my integration tests. The tests fail, and give an exception I've never seen before: NHibernate.ADOException : cannot open connection ----> System.BadImageFormatException : An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B) I've searched online for this exception - It's of course a problem with nUnit, despite the NHibernate exception (remember, NHibernate allows me to hydrate and persist objects when I run the app). I upgraded my nUnit assembly to the most recent release, version 2.5.10, and updated the reference in the project to the assembly under the 'net-2.0' folder of the nUnit zip file. I ran the tests again, and received the same exception. It seems that there is some sort of 32-bit vs 64-bit conflict between assemblies, code, and the ASP.NET Development Server. I don't have any experience dealing with 32-bit vs 64-bit issues, so I don't know if there are other questions on stack overflow that are relevant (the ones I've seen seem not to be). I have some ideas, but no answers: * *Do I need a different nUnit assembly? *Do I need to change the Solution Platform setting in VS2010? (It's currently on "Any CPU") *Do I need to change build properties of my integration tests project? *Do I need to change configuration settings of my solution? Unfortunately I don't have a 32-bit machine around to test the code on at the moment. Are any of the above questions on the right path to solving this? Can you offer any guidance? Thanks. UPDATE: I'm really hoping to be able to run the tests from within Visual Studio using TestDriven.NET. I don't want to have to start using the nunit UI to run my tests. UPDATE 2: Sorry, I may not have been clear. I'm not yet using TestDriven.NET, what I said is that I'm hoping to use it, but I haven't installed it yet on the new x64 machine. At this moment, I'm trying to run the tests by clicking on the visual icon inside the Visual Studio IDE, as in the image below: Following through with that action, the tests fail, and the dialog that pops up displays the following: That is the exception that I quoted up above. There is no reference to assemblies that haven't loaded. At first I didn't believe that the version of NHibernate (2.0.1.4000) I am using would matter; I say this because the providers are able to return the desired objects from the database when the app is run. However, When I debug the test, I see that the exception is being thrown in my provider. When digging down a bit, It seems the source of this is my SQLite assembly. But again, this is the same assembly that works when I run the project - why would it not work when I run the integration tests? A: The nUnit-x86.exe is the 32 bit executable whereas nUnit.exe is the 64-bit one. So use the 32-bit executable to see if that solves things. Use AnyCPU for DLLs. It's the setting for the exe that loads the dll that causes this problem. (32 bit exe cannot load 64 bit dlls or vice versa). A: This is a problem I get regularly. System.Data.SQLite is a 32 or 64 bit specific assembly as it bundles a native image for SQLite inside the DLL. The NUnit test runner is trying to run it in the wrong mode i.e. a 64-bit assembly in a 32-bit test runner and it's going bang when it tries to make a native call to the SQLite C API. Windows can't do that. I suggest you standardise across all platforms on either 32-bit or 64-bit i.e. your dev environment and your deployment environment. An intermediate fix will be to replace the SQLite DLL with a 64-bit one as available from here: http://system.data.sqlite.org/. this may however break at deploy time at which point you will need to create a build configuration for your live environment which ships the right DLL version (32/64-bit). Getting NUnit to deterministically run in either 32 or 64 bit mode is a pain so I wouldn't bother with that personally. A: It appears from your screenshots that you are using the Resharper test runner. In my experience Resharper's test runner uses the appropriate bitness as specified by the test assembly being loaded in the host environment. As such, if you have a project in your tested stack that depends on a 32-bit (i.e. x86) something (such as a project under test set to build as x86 in the current build configuration, or a project with a reference to an assembly marked as x86) then you would do well to mark everything that consumes that thing (including test projects) to build as x86. Running a test project set to build as x86 through the visual studio resharper test runner appears to load in a 32-bit process and successfully run tests on an assembly that is also marked as x86. Ah, the problems of supporting multiple platforms.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600285", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: In my string, there is a character that I cannot identify that seems to be a space (Regex) I have a string that I need to parse using regex. This string is: http://carto1.wallonie.be/documents/terrils/fiche_terril.idc?TERRIL_id=1 Crachet 7/12 What I try to do is to separate the url and the comment, so I tried: (\S+)\s(.+) but as result, I get: $1 = > http://carto1.wallonie.be/documents/terrils/fiche_terril.idc?TERRIL_id=1 Crachet $2 = > 7/12 So, it seem that first character is not a space! I tried to replace \s by 'X' and got http://carto1.wallonie.be/documents/terrils/fiche_terril.idc?TERRIL_id=1 CrachetX7/12 I am sure to have something strange. I tried to replace every character by 'X' (\n, \t, etc.) but cannot find what is this "space lookalike" How can I identify this character and split my string? EDIT: If you want to play with my code, this is a Yahoo! Pipe: http://pipes.yahoo.com/pipes/pipe.edit?_id=a732be6cf2b7cb92cec5f9ee6ebca756 According to the Pipes documentation, it looks like it uses fairly standard regex syntax. Some tests: and A: Try the regex ^(\S+)\s+(.*)$ with the g and m modifier checkboxes checked.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600286", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: python: why "IndentationError: expected an indented block" for this code? Refer to Listing 9. Iteration and a dictionary >>> d = {0: 'zero', 3: 'a tuple', 'two': [0, 1, 2], 'one': 1} >>> for k in d.iterkeys(): ... print(d[k]) File "<stdin>", line 2 print(d[k]) ^ IndentationError: expected an indented block Why? A: Indentation level of your statements is significant in Python. A: Python 3 doesn't have iterkeys. Just use: for k in d: print(d[k]) or even better: for v in d.values(): print(v) A: Even when using the Python interactive interpreter, you need to make sure you have some indentation for a new block of code. This: >>> for k in d.iterkeys(): ... print(d[k]) Should be this: >>> for k in d.iterkeys(): ... print(d[k]) As an aside: that link has a number of errors in what should be the expected output, possibly some copy/paste problem?
{ "language": "en", "url": "https://stackoverflow.com/questions/7600289", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: High performance "contains" search in list of strings in C# I have a list of approx. 500,000 strings, each approx. 100 characters long. Given a search term, I want to identify all strings in the list that contain the search term. At the moment I am doing this with a plain old dataset using the Select method ("MATCH %term%"). This takes about 600ms on my laptop. I'd like to make it faster, maybe 100-200ms. What would be a recommended approach? Performance is critical so I can trade memory footprint for better performance if necessary (within reason). The list of strings will not change once initialised so calculating hashes would also be an option. Does anyone have a recommendation and which C# data structures are best suited to the task? A: Have you tried the following? list.FindAll(x => x.Contains("YourTerm")).ToList(); For some reason the List.AsParallel().Where(...) is slower than list.FindAll(...) on my PC. list.AsParallel().Where(x => x.Contains("YourTerm")).ToList(); Hope this will help you. A: A trie or suffix tree would help in making this faster - this is essentially what fulltext search (usually) is using. There are implementations in C# you can use, also see this SO thread: Looking for the suffix tree implementation in C#? Also as mentioned by @leppie parallel execution will likely be already provide you with the x3 performance gain you are looking for. But then again you will have to measure closely, without that it's anyone's guess. A: I've heard good things about Lucene.NET when it comes to performing quick full-text searches. They've done the work to figure out the fastest data structures and such to use. I'd suggest giving that a shot. Otherwise, you might just try something like this: var matches = list.AsParallel().Where(s => s.Contains(searchTerm)).ToList(); But it probably won't get you down to 100ms. A: Have you tried loading your strings into a List<string> and then using the Linq extensions Contains method? var myList = new List<string>(); //Code to load your list goes here... var searchTerm = "find this"; var match = myList.Contains(searchTerm); A: public static bool ContainsFast<T>(this IList<T> list, T item) { return list.IndexOf(item) >= 0; } Base on tests that I did, this variation of Contains was about 33% faster on my side. A: According to these benchmarks, the fastest way to check if a string occurs in a string is the following: for (int x = 0; x < ss.Length; x++) for (int y = 0; y < sf.Length; y++ c[y] += ((ss[x].Length - ss[x].Replace(sf[y], String.Empty).Length) / sf[y].Length > 0 ? 1 : 0); Thus, you could: * *Loop through the list using a Parallel.For construct *Implement the code above to check if a string contains what you're looking for. "SS" is the string[] of strings to search; "SF" is the string[] of strings to search for; c[y] is the total count of each one found. Obviously you'd have to adapt them to your List[string] (or whatever data structure you're using). A: You should try to use Dictionary class. It's much faster than List because it's an indexed search. Dictionary<String, String> ldapDocument = new Dictionary<String, String>(); //load your list here //Sample -> ldapDocument.Add("014548787","014548787"); var match = ldapDocument.ContainsKey(stringToMatch);
{ "language": "en", "url": "https://stackoverflow.com/questions/7600292", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: removeEventListener() with a callback with a different context I'm writing a mobile app in PhoneGap, but there seems to be an issue with Webkit and its ability to remove event listeners from its event list when there's a scope context change on the callback. Below is an example: Function.prototype.bind = function(scope) { var fn = this; return function () { fn.apply(scope, arguments); }; }; a = function(){}; a.prototype.tmp = function(e){ var tmp = ddd.q('#tmp'); tmp.className = 'active'; tmp.addEventListener('webkitAnimationEnd',this.tmp2.bind([this,tmp]),false); } a.prototype.tmp2 = function(e){ this[1].removeEventListener('webkitAnimationEnd',this[0].tmp2.bind([this[0],this[1]]),false); this[1].className = 'inactive; var t2 = ddd.q('#tmp2'); t2.className = 'active'; t2.addEventListener('webkitAnimationEnd',this[0].setStart.bind([this,t2]),false); }; Now, in the above code, the event listeners never peel off, and whenever the callback gets invoked, the event listener list becomes rather large -- as demonstrated in Web Inspector. Any ideas on how to remove event listeners when they're done using callbacks that change function scope? A: Can you use something like this jsfiddle example? this is the object on which the click event is fired. self is the A object. Function.prototype.bind = Function.prototype.bind || function(scope) { var fn = this; return function () { fn.apply(scope, arguments); }; }; A = function() {}; A.prototype.click = function (el) { var self = this; var onClick = function () { el.removeEventListener('click', onClick, false); alert("this=" + this + "\nself=" + self + "\nel=" + el + "\nclicked"); } el.addEventListener('click', onClick, false); } A.prototype.toString = function () { return "I am an A!"; } a = new A(); a.click(document.getElementById("a1")); a.click(document.getElementById("a2")); Update 1 - second example is here. Major differences below. function createOnClickHandler (scope, outerThis, el) { var onClick = (function (evt) { el.removeEventListener('click', onClick, false); alert("this=" + this + "\nouterThis=" + outerThis + ", \nel=" + el + "\nclicked"); }).bind(scope); return onClick; } A = function() {}; A.prototype.click = function (el) { var ob = { toString: function () { return "I am an ob!"; } }; el.addEventListener('click', createOnClickHandler(ob, this, el), false); } Update 2 - general example of a one-time event handler that binds your event handler to a particular scope, calls that handler, and unregisters the listener. function createOneTimeHandler (evtName, fn, scope, el) { var bound = fn.bind(scope); var onEvent = function (evt) { el.removeEventListener(evtName, onEvent, false); bound(evt); }; el.addEventListener(evtName, onEvent, false); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7600301", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Valgrind memory leak reported in QT list append I am using a serializer in QT C++. It looks ok but valgrind (memcheck tool) is reporting a memory leak on this function. Valgrind cmd: valgrind --tool=memcheck --leak-check=full QDataStream &operator>>( QDataStream &in, QList<AppNodeRecord *> *objAppNodeListRecord) { quint32 len; in >> len; objAppNodeListRecord->clear(); for(quint32 i = 0; i < len; ++i) { AppNodeRecord *tmp=new AppNodeRecord; in >> tmp; objAppNodeListRecord->append(tmp); if (in.atEnd()) break; } return in; } Valgrind reports that this instance is not freed but it is been used in the QList. AppNodeRecord *tmp=new AppNodeRecord; Valgrind output: ==19503== 1,445 (68 direct, 1,377 indirect) bytes in 1 blocks are definitely lost in loss record 1,540 of 1,568 ==19503== at 0x4026351: operator new(unsigned int) (vg_replace_malloc.c:255) ==19503== by 0x8058562: operator>>(QDataStream&, QList<AppNodeRecord*>*) (zbDbs_NodeMgmt.cpp:206) ==19503== by 0x804D53C: main (main.cpp:53) Could it be a valgrind issue? A: The QList isn't responsible for deallocating the AppNodeRecord pointers you append to it, you have to do it manually (qDeleteAll might help in that case). But as usual, for lack of a good reason, use QList<AppNodeRecord> to avoid this hassle in the first place. A: Valgrind memcheck only tells you that there is a memory leak. If, as in your case, there is one, it reports the function where the memory allocation happened (the new statement). To get rid of this leak, you have to delete all the elements that have been dynamically allocated. In your case, as Idan K wrote, you can use the generic Qt algorithm qDeleteAll(objAppNodeListRecord)for instance in the destructor of your class or you can use a more explicit version as follow: foreach (AppNodeRecord *element, objAppNodeListRecord) { delete element; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7600303", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add a pid_t to a string in c I am experienced in Java but I am very new to C. I am writing this on Ubuntu. Say I have: char *msg1[1028]; pid_t cpid; cpid = fork(); msg1[1] = " is the child's process id."; How can I concatenate msg1[1] in such a way that when I call: printf("Message: %s", msg1[1]); The process id will be displayed in front of " is the child's process id."? I want to store the whole string in msg1[1]. My ultimate goal isn't just to print it. A: Easy solution: printf("Message: %jd is the child's process id.", (intmax_t)cpid); Not so easy, but also not too complicated solution: use the (non-portable) asprintf function: asprintf(&msg[1], "%jd is the child's process id.", (intmax_t)cpid); // check if msg[1] is not NULL, handle error if it is If your platform doesn't have asprintf, you can use snprintf: const size_t MSGLEN = sizeof(" is the child's process id.") + 10; // arbitrary msg[1] = malloc(MSGLEN); // handle error if msg[1] == NULL if (snprintf(msg[1], MSGLEN, "%jd is the child's process id.", (intmax_t)cpid) > MSGLEN) // not enough space to hold the PID; unlikely, but possible, // so handle the error or define asprintf in terms of snprintf. It's not very hard, but you have to understand varargs. asprintf is very useful to have and it should have been in the C standard library ages ago. EDIT: I originally advised casting to long, but this isn't correct since POSIX doesn't guarantee that a pid_t value fits in a long. Use an intmax_t instead (include <stdint.h> to get access to that type).
{ "language": "en", "url": "https://stackoverflow.com/questions/7600304", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Prevent javascript from being cached in browser I'm currently working on a webapp and the Javascript is revised fairly often. However, the changes don't occur until the browser cache is refreshed manually. Is there a way to implement cache-refreshing automatically through code for Chrome? Thanks. A: You can put something like ?2352352 at the end of your JS file. So something like <script src='myfile.js?20457207'></script> Where the number randomizes, forcing the browser to think it's a different file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600310", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android smoothScrollBy behaving badly I have a ListView that I am calling smoothScrollBy() on. 95% of the time, the smoothScrollTo() behaves as intended. However there are times that it does not end up in the intended spot! I have verified that I am giving it the same value. I notice that the smooth scrolling is not so smooth when the errors are made, however there are no other tasks that my application is performing that I would have control over. I am not quite sure what is going on in the background but a likely culprit is garbage collection. 95% accuracy is not good enough in this situation. I am going to have to implement some sort of a correction mechanism to make sure the ListView lands on the correct spot in these instances. Is there a better way to use smoothScrollBy() other than simply calling view.smoothScrollBy(distance, time);? A: sometimes it will be because of the timing issue. When the views are added to your listview and the time you do view.smoothScrollBy(distance, time); the listview or the ui still need not get refreshed. So do this in the views post thread with a specific delay. Eg. view.postDelayed(new Runnable{ view.smoothScrollBy(distance, time); },1000); A: Try some of these: Listview has its own scrolling mechanism. It scrolls when the content is added. * *Assign listview height (android:layout_height) to match_parent or fill_parent. *If your assigning a adapter in a working thread. Do not perform any UI actions in the thread. If these do not solve the issue. Please post the code where you assign the adapter to the list view if any. Or the relevant code. Also the xml layout code. Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600312", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "49" }
Q: Find Command that returns line number of the string I have a bunch of files organized into directories..All these are text files (c/c++). I am trying to understand this code and i need to look at the declarations of many variables..How can i use find command to get the exact location( File Name with line number(s) ) using Find command in ubuntu linux?? Or is there any graphical tool for doing the same? A: find . -name *.c -exec grep -Hn "your search term here" {} \; If you really want to use find. EDIT explanation find . -name *.c - find files in current dir and below where name is like *.c -exec - execute command that follows grep -Hn - grep and print results with file name and line number of match {} \; - {} marks where the name of each file found will be substituted and the backslash- semicolon marks the end of the command to execute. A: You can do this with grep. grep -n 'search-term' *.c will give you the filename and line number where the term appears.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600313", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Wordpress Sticky Posts with Custom Post Types So i need the ability to have a featured or "sticky" post in wordpress, and it occurred to me! Why not use the Sticky Posts facility, but after doing a bit of reading it seems that Wordpress decided to not include support for it in latest releases and they don't seem to be pushing any solution for future releases. Now that leaves me in a predicament i wish to have the ability to have a featured post or custom post without using a category of such. I've also seen a few people state they have hacked wordpress with possibly a function to add the ability of sticky posts to custom post types, shame they didn't share the source! How would this be done? A: You can do it with a custom field (post_meta) on the custom post type. Then fire a custom query that selects for the meta_value: $args = array('post_type' => 'my_custom_post_type', 'post_status' => 'publish', 'meta_query' => array('relation' => 'AND', array('key' => 'is_sticky', 'value' => '1', 'compare' => '=', 'type' => 'CHAR'))); $sticky_posts = new WP_Query($args); Should return an array of published posts of post_type: my_custom_post_type that have the sticky flag set. Although I haven't tested the above code, I'm doing something similar and it works fine. A: You can use this plugin, it has it's own limitations, but works pretty well if you don't need something elaborate. A: You can save a custom meta with the name of "sticky" and add it the value "on" when the post is sticky. That can be done with a custom metabox and a checkbox. Wordpress will automatically add the word "Sticky" on the backend posts listing table You can retrieve a loop with your sticky custom posts by adding the values 'meta_key' => 'sticky' and 'meta_value' => 'on' to the args of your query A: I posted a working solution as of WordPress 4.2 here: https://wordpress.stackexchange.com/questions/90958/adding-sticky-functionality-to-custom-post-type-archives/185915#185915 Basically, it implies installing a small plugin and add a code snippet. A: I have Wordpress 3.2.1, the latest version and I can sticky posts. It works for me on my site.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600314", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to sort search result in reverse order of publication date in Google books? Google books provide sorted by date option on the left column to sort searched books. But the result seems that publication date is in descending order ( from latest to oldest). This may not be fit for finding the oldest if there are thousands of search results. How can I quickly locate the oldest book (publication date is the oldest)? Thanks in advance. A: There is currently no way simple way to sort by date in ascending order in Google Books. You can work around this by choosing "Custom Range" and trying out end dates until you get only 1 page of results. Unfortunately, you're still likely to run into the problem that many of the books that Google thinks were published a long time ago are actually metadata errors.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600324", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: What do I need to know going from Java to JavaScript? This isn't as progressive as it sounds. Im not taking the whole "Oh I know Java, that must mean I can write in JavaScript too!" attitude. I have some education on Java under my belt, but now find myself having to do some PHP web development (which I have little experience in) using Java Script to handle some of the logic. But before going out and buying 2 or 3 books on JavaScript and diving right into it, I figure I might ask those that might have gone through the same experience. It appears that JavaScript lives and acts in its own environmnet which makes want to take the approach taking in JavaScript and PHP as a bundled package in my learning endeavors. JavaScript is similar just enough to Java that I will tend to make some dangerous assumptions. Should I treat JavaScript and PHP as one item, or should I still take this step by step and learn one at a time? What are some pitfalls that I might run Into? What are the main differences between the languages? Is there any litterature that has helped? Thanks Everybody. A: What do I need to know going from Java to JavaScript? That they are completely different languages. The Good Parts is a good introduction to the core JS language for existing programmers. You'll also need to learn DOM and other browser APIs if you want to use client side JS for anything practical. Should I treat JavaScript and PHP as one item No. They are completely different. Even when you know both of them you should be writing things that work with plain HTML and PHP, then layering JS on top. A: You should consider the two languages as completely unrelated. All they have in common is that they use { and } to enclose code blocks and ; to terminate statements. They're both object-oriented, but Java is class-based and JavaScript is prototype-based. The only reason JavaScript has the word "Java" in it was because Java was "hot." It's nothing but historical marketing reasons. A: I learned Java script coming from Java myself. I had a bit of trouble with it until I worked with NodeJS a little bit. Learning JS by itself when I wasn`t warring with html and css at the same time made the experience much less painful and made it take less then a couple days. I would really recommend these two books http://www.amazon.com/JavaScript-MooTools-Experts-Voice-Development/dp/1430230541 http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742 Don`t be turned off by the fact the first book is related to a frame work. The first 250 pages are a fantastic JS basics crash course. Of course you are super comfortable with objects and you can find that in Javascript if you really wanted to and never even learn about prototyping and closures. Take the time though to read into these things there are a lot of timing problems that you really can`t solve any other way with respects to asynchronous actions and animation locks. Research functional programming. The hardest thing about the transition is javascripts wonky syntax at first you will hate it but it does finally catch a rhythm. Which reminds me use Lint a lot that will help you catch your syntax issues early. A: Javascript and PHP are both Java-like languages. Just know that Javascript is client-side and shouldn't be bulky. Javascript is also significantly slower as it's a scripted language. Javascript is much easier than PHP as it's more similar to Java. Just note that Javascript is not object-oriented at all.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600325", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Is there a way to invalidate or somehow refresh the cache on MvcSiteMap Currently I have an MvcSiteMap integrated with my ASP.Net MVC app. I need to be able to invalidate or refresh the cache to force a read of the MvcSiteMap. Currently it's cache is set in the web.config to X minutes. It would be nice if I could somehow force a refresh. A: You can specify a 'CacheKey' in your web.config which MvcSiteMap will use as the Http Cache keyname. Then, in your web app, just expire or remove the key from cache. MvcSiteMap has a callback it uses to rebuild the map. Check out the source code at http://mvcsitemap.codeplex.com/SourceControl/changeset/view/b5a6d902d512#Source%2fsrc%2fMvcSiteMapProvider%2fMvcSiteMapProvider%2fDefaultSiteMapProvider.cs - search for cacheKey
{ "language": "en", "url": "https://stackoverflow.com/questions/7600326", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Issues with SBTableAlert.. It shows the alert but not UITableView I don't know if anyone has any experience with SBTableAlert. It looks awesome, but not much documentation. It is also not calling any of the functions that UITableView would use. Can any one help with following code. //load the bookmarks and setup the popup SBTableAlert *bookmarkAlert; bookmarkAlert = [[SBTableAlert alloc] initWithTitle:@"Jump to:" cancelButtonTitle:@"Back" messageFormat:nil]; [bookmarkAlert setDelegate:self]; //[bookmarkAlert setDataSource:self]; NSString *settingsicon = [[NSBundle mainBundle] pathForResource:@"gear" ofType:@"png"]; self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageWithContentsOfFile:settingsicon] style:UIBarButtonItemStylePlain target:bookmarkAlert action:@selector(show)]; A: In the above code you are not setting the datasource. This would be the obvious reason you're not getting what you are looking for, unless you set this later on.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600327", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Are there usually include_path/htaccess restrictions on hosts? My .htaccess file looks like this: php_value include_path "/home/username/public_html/site" and is the same location as the include path. It's causing a 500 internal service error, but was working fine locally. I'm digging around to try and find something via the host but not having much luck. A: Without knowing the exact error message, it is difficult to tell what is going wrong. As Pekka explained, one reason could be that mod_php is not used. This could be the case, for instance if suPHP or any other variant based on PHP's CGI interface is used. If that's the case AND if you are using PHP 5.3.0 or later, you could create a per-directory configuration using a .user.ini file1. So instead of using a .htaccess file with the line php_value include_path "/home/username/public_html/site" you would use a .user.ini containing the line include_path = "/home/username/public_html/site" 1) Note that this is the default file name. The file may have a different name (the file name is configured through the INI directive user_ini.filename) or may be disabled completely. A: In Centos, the default include_path is: .:/usr/share/pear:/usr/share/php
{ "language": "en", "url": "https://stackoverflow.com/questions/7600330", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Sorting ListBox with MVVM code binding I have a ListBox which happily displays data using a code-behind MVVM object. However, I want to sort the entries and so I thought an intermediate CollectionViewSource might work. But instead the program crashes on startup. Original xaml extract: <ListBox SelectedItem="{Binding SelectedCategory}" DisplayMemberPath="name" ItemsSource="{Binding Categories}" Name="CategoriesListBox" /> Code behind extract: public class ViewModel : INotifyPropertyChanged { private trainCategory[] _categories; private trainCategory _selectedCategory; public event PropertyChangedEventHandler PropertyChanged; public trainCategory[] Categories { get { return _categories; } set { if (_categories == value) { return; } _categories = value; RaisePropertyChanged("Categories"); } } //etc Replacement XAML for ListBox: <ListBox SelectedItem="{Binding SelectedCategory}" DisplayMemberPath="name" ItemsSource="{Binding Source={StaticResource SortedItems}}" Name="CategoriesListBox" /> And the CollectionViewSource: <CollectionViewSource x:Key="SortedItems" Source="{Binding Categories}"> <CollectionViewSource.SortDescriptions> <scm:SortDescription PropertyName="name"/> </CollectionViewSource.SortDescriptions> </CollectionViewSource> It seems to me that the CollectionViewSource goes in between the view model and the ListBox, but it clearly doesn't (or I've done it wrong). Any pointers appreciated. A: Use your original xaml <ListBox SelectedItem="{Binding SelectedCategory}" DisplayMemberPath="name" ItemsSource="{Binding Categories}" Name="CategoriesListBox" /> Update your View Model to use a List instead: public List<trainCategory> _categories; public List<trainCategory> Categories { get { // This LINQ statement returns a sorted list return (from c in _categories orderby c select c); } set { if (_categories == value) { return; } _categories = value; RaisePropertyChanged("Categories"); } } //etc Then you can skip all that nastiness of trying to bind to a static resporce. Just bind strait to the property in your view model. Alternately, you can still use arrays as your backing variable in your viewmodel: public trainCategory[] _categories; public List<trainCategory> Categories { get { // This LINQ statement returns a sorted list return (from c in _categories orderby c select c).ToList(); } set { if (_categories == value.ToArray()) { return; } _categories = value.ToArray(); RaisePropertyChanged("Categories"); } } //etc A: What exception are you getting on startup? Remember to have your Resources section before all other code that needs to use the resources. An alternative to that would be: <ListBox SelectedItem="{Binding SelectedCategory}" DisplayMemberPath="name" Name="CategoriesListBox"> <ListBox.ItemsSource> <Binding> <Binding.Source> <CollectionViewSource Source="{Binding Categories}"> <CollectionViewSource.SortDescriptions> <scm:SortDescription PropertyName="name"/> </CollectionViewSource.SortDescriptions> </CollectionViewSource> </Binding.Source> </Binding> </ListBox.ItemsSource> </ListBox> Also remember to have the proper xmlns declaration for scm in any case.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600331", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Chracter codes in sql 'like' queries? I have been putting some data I have into my database. One of the files was somehow corrupted or something - it randomly has the character with value 6, ACK, in various unexpected places in place of real letters. This is causing me various problems with duplications in my database and so on - for instance, one company has two entries in my database, one as Afh Engineering Ltd., the other as Afh Engineerin Ltd. (SO may clean that character - basically the 'g' is replaced with an ACK character.) I want to do a query for all the companies in my database that have this problem. Something like: select * from users where CompanyName like '%06%' but obviously for the character with value '6' rather than the character representing the indo-arabic numeral '6'. How do I do this? A: SELECT * FROM users WHERE CHARINDEX(CHAR(6), CompanyName) <> 0
{ "language": "en", "url": "https://stackoverflow.com/questions/7600333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Using JqueryUI slider to range filter Datatable results I am using the plugin the ColumnFilter to render filters for each column in Datatables. ColumnFilter renders two input boxes (From & To) in order to perform 'range' filtering of a table. I am trying to replace these input boxes with a jqueryUI slider but cannot seem to make it work. I have managed to make a slider control two separate 'from' & 'too' inputs with the following code: //SLIDER $(function() { var $slider = $('#Slider'), $lower = $('input#Min'), $upper = $('input#Max'), min_rent = 0, max_rent = 400; $lower.val(min_rent); $upper.val(max_rent); $('#Slider').slider({ orientation: 'horizontal', range: true, animate: 200, min: 0, max: 400, step: 1, value: 0, values: [min_rent, max_rent], slide: function(event,ui) { $lower.val(ui.values[0]); $upper.val(ui.values[1]); } }); $lower.change(function () { var low = $lower.val(), high = $upper.val(); low = Math.min(low, high); $lower.val(low); $slider.slider('values', 0, low); }); $upper.change(function () { var low = $lower.val(), high = $upper.val(); high = Math.max(low, high); $upper.val(high); $slider.slider('values', 1, high); }); }); This works fine and I can see the values change in the two input boxes change as I move the slider. However, when I swap the input#Min and inut#Max element for the the two input boxes that are rendered by the ColumnFilter plugin. Nothing seems to happen. I cannot see any values update in the input boxes and the table does not auto sort as expected. Perhaps I am approaching this the wrong way? Is there any other way to make a slider work with Datatables and the Columnfilter plugin? Many thanks! A: The two input boxes used for filtering are being 'listened to' for change event but updating the values via UI sliders does not trigger this. I had a similar problem and ended up just forcing change() on sliderstop (event triggered by slider on mouseup) because of the dynamic content being loaded on change which I didn't want changing on slide, but you could force change() on slide too. try: $lower.change(); $upper.change(); after updating the values with val(); Should work :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7600338", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: c# 3.0 Casting an interfaced generic type Given these base classes and interfaces public abstract class Statistic : Entity, IStatistic { protected abstract IStatisticsRepository<IStatistic> Repository {get;} ... public class AverageCheckTime : Statistic ... public interface IStatisticsRepository<T> : IRepository<T> where T : IStatistic ... public interface IAverageCheckTimeRepository : IStatisticsRepository<AverageCheckTime> ... public class AverageCheckTimeRepository : StatisticRepository<AverageCheckTime>, IAverageCheckTimeRepository ... public class RepositoryFactory { public static IAverageQueueTimeRepository AverageQueueTimeRepository { get { return CurrentServiceLocator.GetInstance<IAverageQueueTimeRepository>(); } } Why does AverageCheckTime's implementation throw an invalid cast exception: protected override IStatisticsRepository<IStatistic> Repository { get { return (IStatisticsRepository<IStatistic>)RepositoryFactory.AverageCheckTimeRepository; } } How do I cast an instance of IAverageCheckTimeRepository as an IStatisticsRepository<IStatistic> which I assumed it already was? OK, I've made these changes...which makes me wonder if I've gone over the top with the generics in the first place public interface IStatisticsHelper { void GenerateStatistics(); List<IStatistic> BuildReport(); } ... public interface IStatisticsRepository<T> : IRepository<T>, IStatisticsHelper where T : IStatistic { } ... public abstract class Statistic : Entity, IStatistic { protected abstract IStatisticsHelper Repository { get; } ... public class AverageCheckTime : Statistic { protected override IStatisticsHelper Repository { get { return RepositoryFactory.AverageCheckTimeRepository; } } A: No, C# 3 does not support generic variance. C# 4 does, but you would have to declare that IStatisticsRepository is covariant in T: public interface IStatististicsRepository<out T> : IRepository<T> where T : IStastistic Variance isn't safe in general - it depends on how the generic type parameter is used. C# 4 supports both covariance and contravariance for type arguments which are reference types, but only when the generic type involved is an interface or a delegate, and only when the type parameter is used in the appropriate way within the interface/delegate. Without seeing the declaration for IRepository<T>, we can't tell whether or not it's safe. For example, if IRepository<T> contains a method like this: void Save(string id, T value); then it wouldn't be safe, because you'd be able to write: IStatisticsRepository<IStatistic> repo = RepositoryFactory.AverageCheckTimeRepository; IStatistic foo = new SomeOtherStastisticType(); repo.Save("Foo", foo); That would be trying to save a SomeOtherStatisticType value in an AverageCheckTimeRepository, which violates type safety. It's only safe to make the interface covariant in T if values of type T only come "out" of the interface. (There are some wrinkles around exactly what that means, mind you...) For a lot more information on this, see Eric Lippert's blog series on the topic.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600345", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is a nonstatic member function? I am being told that I can't use the 'this' keyword in a class function. I'm coming from c# and i'm used to this working, but the compiler tells me that it can only be used within nonstatic member functions. D3DXVECTOR3 position; void Position(D3DXVECTOR3 position) { this.position = position; } A: Not only is Position a free function (not associated with a class) the way you wrote it, but this is also a pointer, not a reference. D3DXVECTOR3 position; void ClassName::Position(D3DXVECTOR3 position) { this->position = position; } or, if that's supposed to be a constructor, ClassName::ClassName(D3DXVECTOR3 p) : position(p) { } A: this is a pointer containing the address of the object. D3DXVECTOR3 position; void YourClassNameHere::Position(D3DXVECTOR3 position) { this->position = position; } Should work. D3DXVECTOR3 position; void YourClassNameHere::Position(D3DXVECTOR3 position) { (*this).position = position; } Should also work. A: In C++ you need to qualify your Position function with the class name: void YourClassNameHere::Position(D3DXVECTOR3 position) Also from @Pubby8's answer this is a pointer, not a reference so you need to use this->position instead (or consider using parameter names that don't shadow class members - I like using trailing _ on my class members). Also, C++ doesn't pass by reference by default so if D3DXVECTOR3 is a complicated type you'll be copying a lot of data around. Consider passing it as const D3DXVECTOR3& position instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600346", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Rails API design without disabling CSRF protection Back in February 2011, Rails was changed to require the CSRF token for all non-GET requests, even those for an API endpoint. I understand the explanation for why this is an important change for browser requests, but that blog post does not offer any advice for how an API should handle the change. I am not interested in disabling CSRF protection for certain actions. How are APIs supposed to deal with this change? Is the expectation that an API client makes a GET request to the API to get a CSRF token, then includes that token in every request during that session? It appears that the token does not change from one POST to another. Is it safe to assume that the token will not change for the duration of the session? I don't relish the extra error handling when the session expires, but I suppose it is better than having to GET a token before every POST/PUT/DELETE request. A: Rails works with the 'secure by default' convention. Cross-Site or Cross-Session Request Forgery requires a user to have a browser and another trusted website. This is not relevant for APIs, since they don't run in the browser and don't maintain any session. Therefore, you should disable CSRF for APIs. Of course, you should protect your API by requiring HTTP Authentication or a custom implemented API token or OAuth solution. A: Old question but security is important enough that I feel it deserves a complete answer. As discussed in this question there are still some risk of CSRF even with APIs. Yes browsers are supposed to guard against this by default, but as you don't have complete control of the browser and plugins the user has installed, it's should still be considered a best practice to protect against CSRF in your API. The way I've seen it done sometimes is to parse the CSRF meta tag from the HTML page itself. I don't really like this though as it doesn't fit well with the way a lot of single page + API apps work today and I feel the CSRF token should be sent in every request regardless of whether it's HTML, JSON or XML. So I'd suggest instead passing a CSRF token as a cookie or header value via an after filter for all requests. The API can simply re-submit that back as a header value of X-CSRF-Token which Rails already checks. This is how I did it with AngularJS: # In my ApplicationController after_filter :set_csrf_cookie def set_csrf_cookie if protect_against_forgery? cookies['XSRF-TOKEN'] = form_authenticity_token end end AngularJS automatically looks for a cookie named XSRF-TOKEN but feel free to name it anything you want for your purposes. Then when you submit a POST/PUT/DELETE you should to set the header property X-CSRF-Token which Rails automatically looks for. Unfortunately, AngualrJS already sends back the XSRF-TOKEN cookie in a header value of X-XSRF-TOKEN. It's easy to override Rails' default behaviour to accomodate this in ApplicationController like this: protected def verified_request? super || form_authenticity_token == request.headers['X-XSRF-TOKEN'] end For Rails 4.2 there is a built in helper now for validating CSRF that should be used. protected def verified_request? super || valid_authenticity_token?(session, request.headers['X-XSRF-TOKEN']) end I hope that's helpful. EDIT: In a discussion on this for a Rails pull-request I submitted it came out that passing the CSRF token through the API for login is a particularly bad practice (e.g., someone could create third-party login for your site that uses user credentials instead of tokens). So cavet emptor. It's up to you to decide how concerned you are about that for your application. In this case you could still use the above approach but only send back the CSRF cookie to a browser that already has an authenticated session and not for every request. This will prevent submitting a valid login without using the CSRF meta tag.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600347", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "50" }
Q: Values are incorrect while using String.Format I need to convert a decimal value into something like 0.3 = USDC000000000030 The code i wrote is as below. transactionAmount = String.Format("USDC{0}", ((int)(amount*100)).ToString("D12")); However, it is working for some values perfectly like the example given above. For other some values it is conversion is wrong for example 0.9 = USDC000000000089 1 = USDC000000000099 1.1 USDC000000000109 Any idea why is it happening so? Thanks in advance A: You're probably using double, which for financial values is a huge mistake. Use decimal instead, and wash your troubles away. To wit: decimal amount = 0.3m; string s = String.Format("USDC{0:000000000000}", 100 * amount); Console.WriteLine(s); Output: USDC000000000030 Note that the language specification states: The decimal type is a 128-bit data type suitable for financial and monetary calculations. A: Try this instead: String.Format("USDC{0:D12}", (int)(Convert.ToDecimal(amount) * 100)); Tested with the following: * *0.90 = USDC000000000090 *1.00 = USDC000000000100 *0.89 = USDC000000000089 *0.84 = USDC000000000084 *1.10 = USDC000000000110
{ "language": "en", "url": "https://stackoverflow.com/questions/7600349", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javascript: to change class width from 0% to 100% and from 100% to 0% non stop The code below changes the width of the "inner" class from 0% to 100%, so the bar is filled progressively with the green color. But this is incomplete because once the width is 100% I need it to go back to 0% and then to 100% and so on .. it will only stop going from 0% to 100% and from 100% to 0% when clicked. I'll figure out how to add the clicking even but please help me achieve the non stop changing width. Thanks a ton! <style> .bar { background-color: #191919; border-radius: 16px; padding: 4px; position: relative; overflow: hidden; width: 300px; height: 24px; -webkit-border-radius: 16px; -moz-border-radius: 16px; border-radius: 16px; -webkit-box-shadow: inset 0 1px 2px #000, 0 1px 0 #2b2b2b; -moz-box-shadow: inset 0 1px 2px #000, 0 1px 0 #2b2b2b; box-shadow: inset 0 1px 2px #000, 0 1px 0 #2b2b2b; } .bar .inner { background: #999; display: block; position: absolute; overflow: hidden; max-width: 97.5% !important; height: 24px; text-indent: -9999px; -webkit-border-radius: 12px; -moz-border-radius: 12px; border-radius: 12px; -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.3), inset 0 -1px 3px rgba(0, 0, 0, 0.4), 0 1px 1px #000; -moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.3), inset 0 -1px 3px rgba(0, 0, 0, 0.4), 0 1px 1px #000; box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.3), inset 0 -1px 3px rgba(0, 0, 0, 0.4), 0 1px 1px #000; -webkit-transition: width 0.3s linear; -moz-transition: width 0.3s linear; transition: width 0.3s linear; } .green .inner { background: #7EBD01; background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#7EBD01), to(#568201)); background: -moz-linear-gradient(top, #7EBD01, #568201); } </style> <script type="text/javascript"> for (i=0;i<=100;i++){ setTimeout(function(){ document.querySelector('.green.bar .inner').style.width = i+'%'; },0); } </script> <div class="green bar"> <div class="inner" style="width:0%"></div> </div> A: Fiddle: http://jsfiddle.net/ZeYJy/ I have included two ways to implement my suggestion: The first bar immediately goes back to 0 after reaching 100, the second bar has a small delay. Use the modulo operator % to reset the counter to zero at 100. See below: <script> window.onload = function(){ var counter = 0; window.setInterval(function(){ document.querySelector('.green.bar .inner').style.width = (++counter % 101) + '%'; }, 50); } </script> This script adds an interval on load, which increase the width of the element. After the counter has reached 100, the width will be reset to zero. Explanation of the code: * *var counter = 0 (inside a function, window.onload) - A local variable is defined and initialised at zero. *window.setInterval(function(){ ... }, 50) - An interval is defined, activating the function (first argument) every 50 milliseconds (20x a second, adjust to your own wishes) *(++counter % 101) - Increments the counter by one, modulo 101: The modulo operator calculates the remainder after division, ie: 0 % 101 = 0, 100 % 101 = 100 and 200 % 101 = 99, 201 % 101 = 100, 202 % 101 = 100 A: Instead of setTimeout, use setInterval. Each time the interval is fired, use a function to work out how much to fill the bar. Once it hits 100, reset it. You can then clear the interval using clearInterval once the user has clicked. A: This article shows how to repeat a CSS animation infinitely. This will be easier on your CPU than using Javascript: http://developer.apple.com/library/safari/#codinghowtos/Mobile/GraphicsMediaAndVisualEffects/_index.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7600353", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting List of Volumes always Says C:\ Why The Following Code always reports C:\ although It reports different Device Name handle = FindFirstVolumeW(volName, sizeof(volName)); do{ wchar_t wVolName[MAX_PATH]; QString::fromWCharArray(volName).toWCharArray(wVolName);//make a copy of volName on wVolName wVolName[wcslen(volName)-1] = L'\0'; wchar_t wDeviceName[MAX_PATH]; int charCount = 0; charCount = QueryDosDeviceW(&wVolName[4], wDeviceName, ARRAYSIZE(wDeviceName)); qDebug() << QString::fromWCharArray(wVolName) << "Device: " << QString::fromWCharArray(wDeviceName);//print wVolName and wDeviceName wchar_t driveName[MAX_PATH]; GetVolumePathName(wDeviceName, driveName, MAX_PATH); CloseHandle(handle); qDebug() << QString::fromWCharArray(driveName); }while(FindNextVolume(handle, volName, sizeof(volName))); FindVolumeClose(handle); Output: "\\?\Volume{5c77cc58-d5ab-11e0-a0ec-806d6172696f}" Device: "\Device\HarddiskVolume2" "C:\" "\\?\Volume{5c77cc59-d5ab-11e0-a0ec-806d6172696f}" Device: "\Device\HarddiskVolume3" "C:\" "\\?\Volume{5c77cc57-d5ab-11e0-a0ec-806d6172696f}" Device: "\Device\CdRom0" "C:\" "\\?\Volume{5c77cc56-d5ab-11e0-a0ec-806d6172696f}" Device: "\Device\Floppy0" "C:\" "\\?\Volume{8d974f2c-e9a1-11e0-b7da-0013d407432f}" Device: "\Device\Harddisk1\DP(1)0- 0+8" "C:\" Why doesn't it report D, E, etc .. EDIT and How can I derive the Drive Letter assigned to the Volume A: The documentation for the function says it all: You must specify a valid Win32 namespace path. If you specify an NT namespace path, for example, "\DosDevices\H:" or "\Device\HardDiskVolume6", the function returns the drive letter of the current volume, not the drive letter of that NT namespace path. By the way, a volume can be mounted to multiple drive letters (a drive name like C: is nothing more than a symlink in the NT namespace), so it doesn't really make sense to translate in this manner. A: From the GetVolumePathName documentation: If you specify a relative directory or file name without a volume qualifier, GetVolumePathName returns the drive letter of the current volume. A: Perhaps because you are calling CloseHandle while in the loop: don't do that. It looks like you modeled your code after http://msdn.microsoft.com/en-us/library/cc542456%28v=vs.85%29.aspx: you'll notice the only time they call CloseHandle is AFTER the entire loop is done.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600373", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SSRS report to display Outlook type calendar - People x Days x Activities I am after a pattern/view/opinion/tip/weblink from an SSRS/SQL expert on how I might create a report that enables me to list something like the following: [----Person----]  | [29-Sep-11] | [30-Sep-11] | [01-Oct-11] | [02-Oct-11] | [03-Oct-11]... and so on... Bob Bobertson |   Activity A   |   Activity B    | ----Empty--- |   Activity C   | ---Empty--- | Rob Robertson |   Activity D   |   Activity E   |    Activity F   |   Activity G  | ---Empty--- | ...and so on... Date columns are dynamic - example, 10 days on from today (rolling window report) Person column is dynamic list based on a user collection So the above table looks pretty simple, but theres an extra dimension/depth to it. I need to get the details for the Activity to create a link to it and style it in the report based on other flags. I'm currently stumped on how to structure my resultset, and then how to Group/Pivot the data into a report structure. Has anyone done similar before? I'm using CRM4.0 for records including Date, Person, ActivityTitle, Billable etc SSRS 2008 for the report building via VS2008 BI studio A: Turns out to be very simple! You can just insert a tablix and chose the date field for the column headers, and the Username for the row labels. Add a formula for the intersect to use more than one of the remaining values, and thats the three dimensions solved! – BennIT Adolf Garlic: Think of the tablix (matrix) control as a "design time pivot table" and you can't go wrong Many thanks for your input Adolf!
{ "language": "en", "url": "https://stackoverflow.com/questions/7600377", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Symfony 2 unique validator I'm trying to validate a form with some fields that need to be unique - username and email address. If I submit the form I get a database error. I want to use a validator like I did for everything else - right now I'm trying to use custom getters and isvalidUsername functions in the object and I'm not sure if using the entity manager in the object is the best way to do this. Heres what I'm working with so far... Frontend\UserBundle\Entity\User: properties: email: - NotBlank: ~ - Email: ~ username: - NotBlank: ~ getters: validUsername: - "True": { message: "Duplicate User detected. Please use a different username." } validEmail: - "True": { message: "Duplicate email detected. Please use a different email." } There are built in unique validators in the fosuserbundle but I haven't been able to figure out how to use them. A: I know that this is an old question but I've just had to work this out so I thought I would share my solution. I prefer not to use any bundles to handle my users so this is my manual approach: <?php namespace MyCorp\CorpBundle\Entity; use Symfony\Component\Validator\Mapping\ClassMetadata; use Symfony\Component\Validator\Constraints\NotBlank; use Symfony\Component\Validator\Constraints\Email; use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\Security\Core\User\AdvancedUserInterface; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; /** User - Represent a User object */ class User implements AdvancedUserInterface { /** @var integer $id */ private $id; /** @var string $email */ private $email; /** Constructor, Getters, Setters etc... */ /** Set a list of rules to use when validating an instance of this Class @param Symfony\Component\Validator\Mapping\ClassMetadata $metadata */ public static function loadValidatorMetadata(ClassMetadata $metadata) { $metadata->addPropertyConstraint('email', new MaxLength(255)); $metadata->addPropertyConstraint('email', new NotBlank()); $metadata->addPropertyConstraint('email', new Email()); $metadata->addConstraint(new UniqueEntity(array( "fields" => "email", "message" => "This email address is already in use") )); } } As you can see I define my validation in the model itself. Symfony will call loadValidatorMetadata to let you load validators. A: First of all, I'd recommend you using FOSUserBundle. It's quite flexible and you can save yourself some time you'd spend by fixing subtle bugs and testing if everything really works as intended. Anyway, if you really want to build it yourself, you can at least inspire by bundle I mentioned above. They define custom validator and check for uniqueness in UserManager (validateUnique). Additionally, you have to register it as a service to provide UserManager via constructor injection. Then you just use it as a normal class validator. A: There's the UniqueEntity validation constraint for ensuring that the user provides a unique value for a particular property. Please refer to the documentation for examples using the various formats that Symfony supports. Here's an example using annotations: // Acme/UserBundle/Entity/Author.php namespace Acme\UserBundle\Entity; use Symfony\Component\Validator\Constraints as Assert; use Doctrine\ORM\Mapping as ORM; // DON'T forget this use statement!!! use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; /** * @ORM\Entity * @UniqueEntity("email") */ class Author { /** * @var string $email * * @ORM\Column(name="email", type="string", length=255, unique=true) * @Assert\Email() */ protected $email; // ... }
{ "language": "en", "url": "https://stackoverflow.com/questions/7600379", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Validating names in textboxes in PHP, HTML or Javascript When I type in a name in a textbox on a form, how can I validate that name before the user clicks submit? I see this all the time in CMS and in some forums and never been able to figure it out. Joe A: That depends entirely on what you want to validate. Are you trying to filter out potentially dangerous characters? Is there a format you want names to adhere to? If you want to filter it before the user clicks submit, then you'll need to use Javascript. Read in the value of the textbox, either as the user types it, or after focus is no longer on the textbox, and then inspect the value to see if you're happy with what has been put in. The easiest way to do that is by using regular expressions. Look them up. You can disable the submit button until the text field validates. However, it may still be possible to submit the form, so make sure you do validation on the server side too. Again, it depends entirely on what you want to do - PHP has lots of built-in functions for validating strings to filter out malicious characters, HTML entities, and more. Figure out what you want to do, then look it up in a search engine. A: I am assuming you are talking about seeing if a username is available or if the username is valid - the best way to do this is by using a jQuery plugin. There are plenty of tutorials available online to walk you though the all steps. Such as jQuery Username Availability check.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600381", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Browser unable to open php page? First of all I am showing the PHP code .... <?php echo ("hello"); echo exec("sendip -v -p ipv6 -6s 2001::100 -p tcp -ts 21 -td 21 2001::200 2> &1"); echo ("hi"); ?> When I entered the command through linux command line it is working fine.The command is sending a tcp ipv6 packet on 2001::200 machine from 2001::100. [root@udit-pc]# sendip -v -p ipv6 -6s 2001::100 -p tcp -ts 21 -td 21 2001::200 > /dev/null & /* (-v for verbose) */ Output of above command ... Added 34 options Initializing module ipv6 Initializing module tcp Finalizing module tcp Finalizing module ipv6 Final packet data: 60 00 00 00 `... /* here other packet contents gets printed */ 7D 62 00 00 }b.. 61 62 63 64 abcd Sent 64 bytes to 2001::200 Freeing module ipv6 Freeing module tcp When I execute the php script through command line... [root@udit-pc]# php test.php Freeing module tcp hellohi gets printed and packet arrived at 2001::200. But problem arise when I try to run php script through browser... http:://localhost/test.php hellohi gets printed but packet does not arrive at other machine. sh: sendip: command not found Also in both case packet contents are not printed at terminal although using verbose option but when directly using command verbose option works fine. I tried with many things although I do not think they would help like...... * *I added /usr/local/lib and usr/local/bin to PATH variable but no benefit. *chmod +s /usr/local/bin/sendip .Sticky bit set but again no benefit. *paste the /usr/local/bin/sendip itself in /var/www/html folder although I have changed the PATH variable but as i said i m just using hit n trial getting no clue..... There are some output snapshots which may further help .... [root@cc html]# echo $PATH /usr/lib/qt-3.3/bin:/usr/kerberos/sbin:/usr/kerberos/bin: /usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin: /usr/X11R6/bin:/root/bin:/usr/local/lib [root@cc html]# locate sendip ..... /usr/local/bin/sendip /usr/local/lib/sendip ..... [root@cc bin]# chmod +s sendip [root@cc bin]# ls -l sendip -rwsrwsrwx 1 apache apache 41071 Sep 26 19:41 sendip [root@cc bin]# cd /usr/local/lib/ [root@cc lib]# ls -ld sendip drwxrwxrwx 2 root root 4096 Sep 28 22:48 sendip [root@cc lib]# chmod +s sendip [root@cc lib]# ls -ld sendip drwsrwsrwx 2 root root 4096 Sep 28 22:48 sendip When file contents are changed ....... <?php echo exec("/usr/bin/sendip ........ 2 > &1"); ?> Then oputput is : [root@cc html]# php test.php Freeing module tcp[root@cc html]# On browser.... No error gets printed but packet still not arrived. I am stuck in between.Please suggest me what else should I rather try ??????/ A: is sendip() in the path of the shell being invoked by PHP? You're not checking for error conditions, so possibly you're not actually executing sendip, and just getting a "no such program or file" type errors. Instead of redirecting the exec()'d command's output to null, redirect it all to the browser so you can see what happens: echo exec("sendiip yada yada yada 2>&1"); A: Try using the full path: exec("/usr/lib/sendip -v -p ipv6 -6s 2001::100 -p tcp -ts 21 -td 21 2001::200 > /dev/null &"); A: The server is most likely not running with the same permissions as the user, you are testing with. The server is most likely discarding any PATH variable. Make sure that you specify the complete path to sendip in the exec call. A: The Problem is solved although I can not say its fully solved but as per my need its working. What i did is I re-installed the sendip ,then I set its sticky bit and then after that I set the Path variable to as above mentioned in question. Actually the tool is by default installing the libraries in /usr/local/lib/sendip folder and sendip in /usr/local/bin folder. Although after setting PATH variable still I need to use full path in the PHP Script /usr/local/bin/sendip -v ..... (one of my friend suggested me this..) What I think is PHP Path is something different from Shell PATH.I need to paste sendip to /usr/bin and then I need to run updatedb before setting its sticky bit if I don't want to mention full path in PHP Script .Now this command will work fine in PHP Script. sendip -v ......... Although May be I am wrong but this all works fine for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600382", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ruby on Rails and facebook I am trying to write a code in ruby on rails that would go into facebook and pull out data to populate my database based on key words that I manually add inside the code. Anyone has done something similar or can help me with it by pointing me towards the right direction? Also I need the code to stay "alive" after the first run in order to update my site automatically. I've looked for a fb API but i couldn't find anything. Thanks, Crematorio A: The Facebook Graph API is what you would use to pull out data, typically the feed. As for Ruby on Rails, many ways to interact with the FB Graph, but I think the Koala gem is your ticket: https://github.com/arsduo/koala You would need to set up an application at the FB Developers site, then pass the ID/secret to authenticate via Oauth. I use the following to pull wall feed, this little bit might get you started... oauth = Koala::Facebook::OAuth.new('app ID here', 'app secret here', 'website/project url') graph = Koala::Facebook::GraphAPI.new(oauth.get_app_access_token) feed = graph.get_connections("facebook username here", "feed") @facebook_feed = ActiveSupport::JSON.decode(feed.to_json) Adapt this however you like, what I would probably do is a rake task that checks the results of @facebook_feed and processes them based on criteria, keywords, etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600388", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to configure Joomla 1.7 SMTP email with a google apps email address I have a fresh Joomla 1.7 install. I have a valid, confirmed, working google apps email that I can log into via the web client. I have pop and imap enabled. Configuration within Joomla Global Configuration Tab in the Mail Settings section is as follows: Mailer: SMTP From Email: [-me-]@decherney.com From Name: Test Site Email Sendmail Path: /usr/sbin/sendmail SMTP Authentication: Yes SMTP Security: SSL SMTP Port: 465 SMTP Username: [-me-]@dechereny.com SMTP Password: [-password-] SMTP Host: smtp.gmail.com Anytime the site tries to send email whether for registration, mail, or other notification services it reports the following: SMTP Error! Could not connect to SMTP host. I have tried using port 587, using phpmail with the smtp host as ssl:smtp.gmail.com:465, and pretty much every other solution proposed on the net. If anyone has a suggestion/answer I would be much appreciative. A: turns out all I had to do was add the following line to the php.ini file extension=php_openssl.dll (or uncomment it) A: Try setting the SendMail Path to : smtp.gmail.com Everything else looks good.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600390", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can't figure out how to get rows based on column values that aren't identical My problem is this: Say I hypothetically have a table called fastfood which has one field called fastfood_chains that have values of "Awesome Wendys" and "Peanut Chuck" Then I have another table called fastfood_info that has a field "fastfood_chain" but the values aren't identical to the other table, it's shortened to "Wendys" or "Chucks" How would I display all the rows from fastfood_chain and have the results print the full name using the other table instead of just "Wendys" or "Chucks" ? I assumed it had something to do with the LIKE statement but I'm having difficulties. Any help would be appreciated. A: If You know that fastfood_chain in second table contains only subsets of fastfood_chain from first table. I didn't quite understand what exact columns do You want in the result, but You can list them with fff and ffc prefix: SELECT * FROM fastfood_chains ffc INNER JOIN fastfood_info ffi ON ffc.fastfood_chain LIKE CONCAT('%', ffi.fastfood_chain, '%') Please note that this might be extremely slow depending on many factors. P.S.: I don't have access to MySQL instance at the moment. Hope it works now. For MSSQL users, the last line should be: ffc.fastfood_chain LIKE '%' + ffi.fastfood_chain + '%' A: Possible way of doing this is: SELECT F.FASTFOOD_CHAIN, I.* FROM FASTFOOD F LEFT OUTER JOIN FASTFOOD_INFO I ON F.FASTFOOD_CHAIN LIKE '%' || I.FASTFOOD_CHAIN || '%'
{ "language": "en", "url": "https://stackoverflow.com/questions/7600392", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jBCrypt fails to verify password I'm working on encrypting passwords for my application since the password will be stored in the shared preferences I found bcrypt and read a lot of good things about it but I can not get it to work I'm using jBCrypt. I followed the instructions and did this as a test String hashed = BCrypt.hashpw("dog", BCrypt.gensalt(12)); String candidate = BCrypt.hashpw("dog", BCrypt.gensalt(12)); if (BCrypt.checkpw(candidate, hashed)){ Toast.makeText(Loader.this, "equals", Toast.LENGTH_LONG).show(); }else{ Toast.makeText(Loader.this, "don't match?", Toast.LENGTH_LONG).show(); } However everytime i run the application the toast that displays is don't match? So when I log the hashed password in my shared prefs and then compare it against the user input it says it would say wrong everytime since apparently it's giving me a different hash everytime what's up how can i use this? A: According to the documentation, BCrypt.checkpw() takes the plaintext password as its first argument. So it should be: String hashed = BCrypt.hashpw("dog", BCrypt.gensalt(12)); String candidate = "dog"; if (BCrypt.checkpw(candidate, hashed)) { Toast.makeText(Loader.this, "equals", Toast.LENGTH_LONG).show(); } else { Toast.makeText(Loader.this, "doesn't match?", Toast.LENGTH_LONG).show(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7600395", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Display specific fields from a CSV file I'm very new to PHP. I have looked around at other questions but none of them seem to provide a solution, so hopefully someone can help! I have a csv file, but wish to pick out individual fields instead of displaying a whole column. Is this possible with php? My code so far (below) picks out specific columns which is not quite what I want to do. If it could pick out specific rows, that would be better than what it's currently showing, but ideally I'd be able to pick specific fields out. <table> <?php $handle = fopen("test.csv", "r"); while (!feof($handle) ) { $line_of_text = fgetcsv($handle, 1024, ","); print "<tr><td>" . $line_of_text[0] . "</td><td>" . $line_of_text[5] . "</td></tr>"; } fclose($handle); ?> </table> Hopefully that makes sense! A: fgetcsv() only reads the file line by line, so if you want to skip to a particular line, you'd have to put that in yourself: $desired_line = 17; $current_line = 0; while($line = fgetcsv($handle)) { $current_line++; if ($current_line < $desired_line) { continue; // keep reading more lines until we reach 17. } print blah blah blah; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7600398", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: mvc logging: [LogRequest] vs OnActionExecuting i'm a .net/c# noob (long-time servlet/java developer) i need to add logging to my mvc application. i want it to be fairly cheap performance-wise, and simple to configure. what i would initially like to do is log each incoming controller action. it occurred to me that there might be a single-point-of-entry so i don't have to add a line of code to every controller's action methods. the way i see it, i can either add a [LogRequest] attribute to the controller (in my case, a base controller) and then implement a public class LogsRequestsAttribute : ActionFilterAttribute, IActionFilter { void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext) { ... } } class to handle the logrequest attribute. or i could just override the base controller as per: public class BaseController : Controller { protected override void OnActionExecuting(ActionExecutingContext filterContext) { // perform some action here } } and inherit all my controllers from BaseController. in terms of performance, which would be quicker? also, in terms of performance, i am considering putting the actual logging method call in a non-blocking thread that runs once and dies. any pitfalls with this approach? the goal is to let the app proceed and not wait around for the logging method to finish it's task. A: If you're using MVC3, I'd recommend adding your action filter to the global filters collection rather than requiring a base controller. At app startup, in your Global.asax ("MvcApplication") class, you'll need a line like: GlobalFilters.Filters.Add(new LogRequestsAttribute()); That will run it for all controller actions. From a performance perspective, I don't think you'll see much difference between the attribute or the base controller mechanism. I've not tried it, but since the action filter portion of the MVC pipeline is going to run regardless of you having a base controller, the real consideration here would be flexibility rather than performance. The more flexible design is to isolate the logging from the controller. I'd look at using a third-party log solution like log4net, which is already optimized for speed and well-tested. That will allow you to avoid having to spin up asynchronous logging threads and all that. Just log to log4net in your action filter and call it good. That also allows you to do the async portion of things on a per-appender basis - more control. If you need async logging, write your log4net appender to be asynchronous rather than wrapping all the various logging calls with async behavior.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600400", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: XPath Query C# to pull out nodes dynamically I am having to write a XPath Query to pull out the answer for a question based on the question id. The question id is passed dynamically to the query. I cannot use LINQ as the solution is in NET 2.0. Please find the XML file below <?xml version="1.0" encoding="utf-8" ?> <Questionaire> <question id="1"> <answer>1</answer> <correctAnswer>Text</correctAnswer> </question> <question id="2"> <answer>2</answer> <correctAnswer>Text</correctAnswer> </question> </Questionaire> I'am a novice to XPath and find it hard to get my head around it. Many thanks in advance. A: You could use the XmlDocument class and the SelectSingleNode method to perform XPath queries. You may checkout the following article for examples. In your case the XPath query will be something along the lines of Questionaire/question[id='1'] where the id could be variable of course in order to fetch the corresponding node. Once you find the <question> node corresponding to your search criteria you could navigate to its child nodes. A: Your XPath expression can be dynamically generated like this: myExpression = string.Format("/*/*[id='{0}']/answer", theId); then, depending on the object representing the XML document you need to call one of the following methods: Select(), SelectNodes(), SelectSingleNode(), Evaluate(). Read the MSDN documentation about the appropriate methods of XmlDocument, XPathDocument, XPathNavigator and XPathExpression.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600413", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Modify UISearchBar width in a UITableView header I'm running the following snippet of code (in ViewDidLoad method of a UITableViewController) to create a UISearchBar and add it to a UITableView header. UISearchBar search = new UISearchBar(); search.SizeToFit (); // How to modify width? TableView.TableHeaderView = searchBar; Do you if there is a workaround to modify the width of the UISearchBar. The previous snippet of code allows the bar to have a width as the screen one. Giving a frame to the bar seems not working. Thank you in advance. EDIT: The sample has been created for MonoTouch, but it can apply for iOS in general. A: This is the solution that I found: * *create a UIToolbar *add the UISearchBar to that toolbar *add the toolbar to the header of a UITableView Since in a UIToolbar it is possible to insert space elements (i.e. UIBarButtonItemFlexibleSpace), the width of a search bar can be modified easily.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600414", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails 3 generate migration - no up or down method Just learning rails, am on to migrations and it all started off pretty logically until I hit something odd going on in the code; rails generate migration AddRegionToSupplier The above produces a migration file with only a "def change" method in it. I googled this and found that this is exactly what is supposed to happen; http://guides.rubyonrails.org/migrations.html I would have expected it to generate a "def up" and "def down" method, so that the migration could be rolled back. Have I done something wrong in the generation or am I missing something obvious? A: From the link you pasted: Rails 3.1 makes migrations smarter by providing a new change method. This method is preferred for writing constructive migrations (adding columns or tables). The migration knows how to migrate your database and reverse it when the migration is rolled back without the need to write a separate down method. So it looks like you don't have to worry about having a def self.down as Rails is now smart enough to know how to roll it back.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600415", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to change/prioritize function execution in flex? So basically I have a component with my event dispatched: <components:MyComp id="Id" myDispatchedEvent(event)/> In script tags I have that function: private function myDispatchedEvent(event:Event):void { //Here I have my static function with title and handler function showConfirmation Calculate.showConfirmation("String Title", function(event:Close):void { if(bla bla bla) //lots of code etc. ... }); //myDispatchEvent function continues here.. } So problem is with my static function's showConfirmation handler, if I go through debug, it just skips that function and continues doing myDispatchedEvent. Why doesn't anonymous function inside showConfirmation function execute? Thanks A: Functions are executing upon call. In your case you have just declaration of it. Call this function somewhere inside Calculate.showConfirmation and it will be executed. Something like the following: public class Calculate { public static function showConfirmation(title:String, func:Function):void { // The call I'm talking about is here func(new Close()); } } A: Let me say first that what you're trying to do is quite strange. I'd try to code a different solution, but this depends on what you're trying to do. It you tell us a more about it we could find a better way to reach your goal. BTW, you can do something like this: <?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" minHeight="600" minWidth="955"> <fx:Script> <![CDATA[ import mx.events.CloseEvent; public static function myFunction(param:String, func:Function):void { trace("executing"); func.apply(); } protected function labelx_clickHandler(event:MouseEvent):void { trace("click"); Tests.myFunction("Test", function():void { if (event.localX > 0) { trace("Test"); } else { trace("No"); } }); } ]]> </fx:Script> <s:Button id="labelx" label="Click me" click="labelx_clickHandler(event)"/> </s:Application> Something similar what Constantiner has already told you. If you don't execute the function that you're passing to your static function as a parameter inside this static function, it won't be executed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600417", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pydev with Scapy Gives "Unresolved Import" Error I'm trying to write a program that uses the scapy modules. I'm using PyDev for my development but it keeps giving me errors when I import certain parts of the Scapy module. I'm pretty sure I have my import paths in PyDev set up correctly. I've looked at some of the other questions involving "Unresolved Import" errors on here. However, none of the suggestions I saw seemed to help. The weird thing is that it is only part of the scapy modules that don't work. So for instance PyDev doesn't complain when I do from scapy.all import Ether, sendp However, when I do from scapy.all import IP, UDP I get errors. I thought maybe I was importing the wrong modules but when I go to the interpreter and type in the second example it gives no errors and then I can create IP packets using IP(params), which is what I'm trying to do in my program. I installed scapy using the ubuntu repositories, but when I started having import problems I downloaded the latest version from scapy.net and used the setup script. I even copied the zip and put it in my /usr/local/lib/python2.7/site-packages folder and added it to my python path in PyDev. But nothing seems to get rid of the error. Any suggestions on what could be causing this and how to fix it? A: Have you tried adding 'scapy' to the forced builtins? See: http://pydev.org/manual_101_interpreter.html for details. A: I got a chance to play some more with this. I still don't know why PyDev gives me an import error when it works fine in the interpreter, however, I did find a way around it. To import things like IP, UDP, and TCP I'm now using the following from scapy.layers.inet import IP, TCP, UDP For non IPv4 stuff from scapy.all import <Module Name> seems to work just fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600418", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: sqlalchemy joined alias doesn't have columns from both tables All I want is the count from TableA grouped by a column from TableB, but of course I need the item from TableB each count is associated with. Better explained with code: TableA and B are Model objects. I'm trying to follow this syntax as best I can. Trying to run this query: sq = session.query(TableA).join(TableB).\ group_by(TableB.attrB).subquery() countA = func.count(sq.c.attrA) groupB = func.first(sq.c.attrB) print session.query(countA, groupB).all() But it gives me an AttributeError (sq does not have attrB) I'm new to SA and I find it difficult to learn. (links to recommended educational resources welcome!) A: When you make a subquery out of a select statement, the columns that can be accessed from it must be in the columns clause. Take for example a statement like: select x, y from mytable where z=5 If we wanted to make a subquery, then GROUP BY 'z', this would not be legal SQL: select * from (select x, y from mytable where z=5) as mysubquery group by mysubquery.z Because 'z' is not in the columns clause of "mysubquery" (it's also illegal since 'x' and 'y' should be in the GROUP BY as well, but that's a different issue). SQLAlchemy works the same exact way. When you say query(..).subquery(), or use the alias() function on a core selectable construct, it means you're wrapping your SELECT statement in parenthesis, giving it a (usually generated) name, and giving it a new .c. collection that has only those columns that are in the "columns" clause, just like real SQL. So here you'd need to ensure that TableB, at least the column you're dealing with externally, is available. You can also limit the columns clause to just those columns you need: sq = session.query(TableA.attrA, TableB.attrB).join(TableB).\ group_by(TableB.attrB).subquery() countA = func.count(sq.c.attrA) groupB = func.first(sq.c.attrB) print session.query(countA, groupB).all() Note that the above query probably only works on MySQL, as in general SQL it's illegal to reference any columns that aren't part of an aggregate function, or part of the GROUP BY, when grouping is used. MySQL has a more relaxed (and sloppy) system in this regard. edit: if you want the results without the zeros: import collections letter_count = collections.defaultdict(int) for count, letter in session.query(func.count(MyClass.id), MyClass.attr).group_by(MyClass.attr): letter_count[letter] = count for letter in ["A", "B", "C", "D", "E", ...]: print "Letter %s has %d elements" % letter_count[letter] note letter_count[someletter] defaults to zero if otherwise not populated.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600420", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Populate list view I am developing a final year project and I am stuck at a point. I have to retrieve names of doctors from my database (MySQL database) and show it in a list view. I was able to establish a connection with the server and retrieve values, but when I tried to show the values in a list view, the application crashed! I tried the same example given in [Hello, Views, List View][4]. It works for a predefined array like private String lv_arr[]={"Android","iPhone","BlackBerry","AndroidPeople"}; but for a string array retrieved from the database it shows a run time exception. Is there any way I can achieve this? package com.proj; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.widget.*; import android.app.ListActivity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.widget.LinearLayout; import android.widget.TextView; public class proj extends ListActivity { /** Called when the activity is first created. */ public int n=0; public int t=0; public int i=0; public String name[]=new String[30]; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Create a crude view - this should really be set via the layout resources // but since its an example saves declaring them in the XML. TextView txt=(TextView)findViewById(R.id.tv);; //Call the method to run the data retrieval getServerData(KEY_121); setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, name)); } public static final String KEY_121 = "http://10.0.2.2/doc.php"; //I use my real IP address here. private String getServerData(String returnString) { InputStream is = null; String result = ""; //The year data to send. ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("year","1970")); //HTTP post try{ HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(KEY_121); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch(Exception e){ Log.e("log_tag", "Error in http connection "+e.toString()); } //Convert response to string try{ BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result=sb.toString(); } catch(Exception e){ Log.e("log_tag", "Error converting result "+e.toString()); } //Parse JSON data try { JSONArray jArray = new JSONArray(result); for(i=0;i<jArray.length();i++) { JSONObject json_data = jArray.getJSONObject(i); n=jArray.length(); name[i]=json_data.getString("name"); //Get an output to the screen returnString += "\n\t" + jArray.getJSONObject(i); } } catch(JSONException e) { Log.e("log_tag", "Error parsing data "+e.toString()); e.printStackTrace(); } return returnString; } } A: You are using 1.) android:id="@+id/list" inside the ListView, but if your extend an activity by ListActivity you have to use android:id = "@android:id/list" 2.) You return a String[] here, not String private String[] getServerData(String returnString) { ....... JSONArray jArray = new JSONArray(result); name = new String[jArray.length()]; for(i=0;i<jArray.length();i++) { JSONObject json_data = jArray.getJSONObject(i); name[i]=json_data.getString("name"); } return name; } And in ArrayAdapter, do it like this: ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, getServerData(KEY_121)); setListAdapter(adapter); A: public String name[]; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Create a crude view - this should really be set via the layout resources // but since its an example saves declaring them in the XML. TextView txt=(TextView)findViewById(R.id.tv);; ... ... try { JSONArray jArray = new JSONArray(result); name[]=new String[jArray.length()]; for(i=0;i<jArray.length();i++) { JSONObject json_data = jArray.getJSONObject(i); n=jArray.length(); name[i]=json_data.getString("name"); //Get an output to the screen returnString += "\n\t" + jArray.getJSONObject(i); } } catch(JSONException e) { Log.e("log_tag", "Error parsing data "+e.toString()); e.printStackTrace(); } It seems that initializing name[] with a size of 30 may be too small.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600422", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using Django to summarize Report I'm trying to produce a table that will show the total maturity amounts for each financial institution that a plan has. A plan is the term I use for person. So each person can have multiple investments. I'm having trouble creating a table that will do this correctly. Currently I have a report that displays each investment sorted by Maturity Date, i.e. 2011,2012, etc. At the bottom I would like to place this summary table, but my query displays duplicates of each financial institution, due to being able to have multiple investments. My current query: list = Investment.objects.all().filter(plan = plan).order_by('financial_institution').filter(maturity_date__gte= '%s-1-1' % current_year).distinct() This will output: * *TD Bank $10k *TD Bank $10k *Scotia Bank $10k *Etc But I'd like: * *TD Bank $20k *Scotia Bank $10k *Etc A: So, you want to aggregate the values of the investments for a plan: from django.db.models import Sum my_plan.investment_set.filter( maturity_date__gte=whenever ).values('financial_institution').annotate(Sum('value'))
{ "language": "en", "url": "https://stackoverflow.com/questions/7600431", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What source comments does Xcode recognize as tags? This is mostly for curiosity's sake. I've known for awhile that Xcode is capable of recognizing comments in the form of // TODO: Something I don't feel like doing now. Adding that line to the source of a file will cause that TODO comment to show up in Xcode's navigation bar: I also recently discovered that comments of the form // MARK: Something can achieve the same effect as #pragma marking something. So I can write a comment that looks like: // MARK: - // MARK: Future Improvements: // TODO: Make something better // TODO: Fix some bug And Xcode will render it out like this: Which leads me to wonder: Are there other kinds of comments that Xcode can understand to improve project navigation? A: There is also MARK, FIXME, !!! and ???, e.g. // FIXME: this bug needs to be fixed and // ???: WTF ??? You can see where these are defined in /Applications/Xcode.app/Contents/OtherFrameworks/XcodeEdit.framework/Versions/A/Resources/BaseSupport.xclangspec (or /Developer/Library/PrivateFrameworks/XcodeEdit.framework/Resources/BaseSupport.xclangspec for older versions of Xcode). Presumably you could also add your own tags here if you wanted to but I have not actually tried this. Here is the relevant section in BaseSupport.xclangspec: { Identifier = "xcode.lang.comment.mark"; Syntax = { StartChars = "MTF!?"; Match = ( "^MARK:[ \t]+\(.*\)$", "^\(TODO:[ \t]+.*\)$", // include "TODO: " in the markers list "^\(FIXME:[ \t]+.*\)$", // include "FIXME: " in the markers list "^\(!!!:.*\)$", // include "!!!:" in the markers list "^\(\\?\\?\\?:.*\)$" // include "???:" in the markers list ); // This is the order of captures. All of the match strings above need the same order. CaptureTypes = ( "xcode.syntax.mark" ); Type = "xcode.syntax.comment"; }; }, These tags are also supported in the BBEdit text editor and its freeware sibling TextWrangler. A: Looks like // MARK: // TODO: // FIXME: // ???: // !!!: all get translated into #pramga-like markers. It appears that they stand for // Mark, as in pragma // To Do note // Known bug marker // Serious question about form, content, or function // Serious concern about form, content, or function A: You can use // MARK: - with tags below as per Apple example // MARK: UICollectionViewDataSourcePrefetching /// - Tag: Prefetching
{ "language": "en", "url": "https://stackoverflow.com/questions/7600435", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "40" }
Q: How to send message to news feed with facebook sdk php I would like to send message to news feed of user, i'm doing it with the code bellow but it does not go to news feed, it only go to user page. <?php require "src/facebook.php"; $facebook = new Facebook(array( 'appId'=>'xxx', 'secret'=>'xxx', 'cookie'=>true )); $usuario = $facebook->getUser(); if(!$usuario) { $login_url = $facebook->getLoginUrl(array('scope'=>'email,publish_stream')); echo "<script> document.location=\"".$login_url."\"; </script>"; } $facebook->api('/me/feed','POST',array('message'=>'msg via api','link'=>'www.google.com','privacy'=>array('value'=>'CUSTOM','friends'=>'SELF'))); ?> A: You can't choose what should go to the user's friends' news feed (nor top stories). This is decided by Facebook internal algorithms AND the user's friend.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WinRT - SnapsToDevicePixels? I can't find the SnapsToDevicePixels in the WinRT (.NET 4.5) framework for Windows 8. How come? Was it removed? Are there any other alternatives to decrease bluriness in Windows 8 Metro applications? A: Also see UseLayoutRounding. This can get rid of blurriness on images as well. A: The closest property within the WinRT profile is UseLayoutRounding Since this answer was accepted, and I cannot delete the answer and the fact the original revision wasn't correct, I have simply modified the answer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Detailed documentation of Z3 INI options Is there any detailed documentation of the INI options of Z3. I had to do a trial and error approach to figure out the best options for my QF_BV problems. I am still not sure if there are more options that would make my z3-run faster. It would be great if someone can point to any existing detailed explanation of the INI options. Thanks. A: We are currently restructuring Z3, and moving away from the approach: a solver with “thousand” parameters. We are moving Z3 into a more modular and flexible approach for combining solvers and specifying strategies. You can find more information about this new approach in the following draft. Regarding INI options, several of them are deprecated, and only exist because we didn’t finish the transition to the new approach yet. Several of these options were added for particular projects, and are obsolete now. They only exist for backward compatibility. Regarding QF_BV, Z3 3.2 contains two QF_BV solvers: old (the one from 2.x) and new. The new (official) one is only available in the Z3 official input format: SMT 2.0. SMT 1.0, Simplify and Z3 low level input formats are obsolete. Most of the performance improvements in Z3 3.x are only available when one uses SMT 2.0 input format. In a couple of months, the strategy specification language will be officially supported in Z3. We will have a tutorial and documentation describing how to use it. In the meantime, I strongly recommend that you use the default configuration and the SMT 2.0 input format for logics such as QF_BV.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600444", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I read from a File to an array I am trying to read from a file to an array. I tried two different styles and both aren't working. Below are the two styles. Style 1 public class FileRead { int i; String a[] = new String[2]; public void read() throws FileNotFoundException { //Z means: "The end of the input but for the final terminator, if any" a[i] = new Scanner(new File("C:\\Users\\nnanna\\Documents\\login.txt")).useDelimiter("\\n").next(); for(i=0; i<=a.length; i++){ System.out.println("" + a[i]); } } public static void main(String args[]) throws FileNotFoundException{ new FileRead().read(); } } Style 2 public class FileReadExample { private int j = 0; String path = null; public void fileRead(File file){ StringBuilder attachPhoneNumber = new StringBuilder(); try{ FileReader read = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(read); while((path = bufferedReader.readLine()) != null){ String a[] = new String[3]; a[j] = path; j++; System.out.println(path); System.out.println(a[j]); } bufferedReader.close(); }catch(IOException exception){ exception.printStackTrace(); } } I need it to read each line of string and store each line in an array. But neither works. How do I go about it? A: Do yourself a favor and use a library that provides this functionality for you, e.g. Guava: // one String per File String data = Files.toString(file, Charsets.UTF_8); // or one String per Line List<String> data = Files.readLines(file, Charsets.UTF_8); Commons / IO: // one String per File String data = FileUtils.readFileToString(file, "UTF-8"); // or one String per Line List<String> data = FileUtils.readLines(file, "UTF-8"); A: It's not really clear exactly what you're trying to do (partly with quite a lot of code commented out, leaving other code which won't even compile), but I'd recommend you look at using Guava: List<String> lines = Files.readLines(file, Charsets.UTF_8); That way you don't need to mess around with the file handling yourself at all.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600446", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cannot get context to launch intent I've made a separate class to launch and intent as the class I would like to launch the intent from is a thread and does not inherit from activity and would not launch startActivity. Every time I launch the app I get a null pointer exception for the context. public class ToLaunch extends Activity { public void launchScoreloop() { con.getApplicationContext(); startActivity(new Intent(this, LeaderboardsScreenActivity.class)); } } A: You Are writing an Activity , and you didn't override the method onCreate(). public class ToLaunch extends Activity { @override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); //Call your method here after a button click cor example or something else } public void launchScoreloop() { con.getApplicationContext(); startActivity(new Intent(this, LeaderboardsScreenActivity.class)); } } refer this two tutorials about using intents to start another Activity : tuto 1 tuto 2 And if you want to launch the Activity from another Class , you should pass the context to the second Class like this : SecondClass instance = new SecondClass(this); and the contructor of your SecondClass will be something like this : public void SecondClass(Context _context){ this.context = _context; } and then you can start the Avtivity by using the context that you passed to your SecondClass like this : this.context.startActivity(....); A: If thread is a inner class inside your activity you can use startActivity(new Intent(YourActivity.this, LeaderboardsScreenActivity.class)); If it is a separate class you can make a constructor that take context has constructor as argument and you can pass your activity context into that constructor Context con; public YourThread(Context context){ con = context; } and from inside your activity, while making thread object YourThread thread = new YourThread(this);
{ "language": "en", "url": "https://stackoverflow.com/questions/7600447", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Switch focus between opened dialogs is there any way to programmatically switch focus between shown dialogs? To resume... I need method dialog.requestFocus(), but there is no some like that... Thanks... A: Well this thing that you want to do it is not user friendly you shouldnt do things like this. The dialogs are modal so you should pop it out prompting the user to do some action chose some decision and so on after that the dialog should vanish :)... Things like requestFocus() it is stupid to be present in the component like dialog on android, cause when the dialog is visible it is logical that it is focused.... BUT,for your pleasure you can do the flowing: when you decide that you should change the focus hide the dialog A like dialogA.dismiss() and dialogB.show();, if you decide to back to A than dialogA.show();, dialogB.dismiss();... this is simple hack but if you code syntactically correct it will work
{ "language": "en", "url": "https://stackoverflow.com/questions/7600449", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to prevent page scrolling when scrolling a DIV element? I have reviewed and tested the various functions for preventing the body ability to scroll whilst inside a div and have combined a function that should work. $('.scrollable').mouseenter(function() { $('body').bind('mousewheel DOMMouseScroll', function() { return false; }); $(this).bind('mousewheel DOMMouseScroll', function() { return true; }); }); $('.scrollable').mouseleave(function() { $('body').bind('mousewheel DOMMouseScroll', function() { return true; }); }); * *This is stopping all scrolling where as I want scrolling to still be possible inside the container *This is also not deactivating on mouse leave Any ideas, or better ways of doing this? A: If you don't care about the compatibility with older IE versions (< 8), you could make a custom jQuery plugin and then call it on the overflowing element. This solution has an advantage over the one Šime Vidas proposed, as it doesn't overwrite the scrolling behavior - it just blocks it when appropriate. $.fn.isolatedScroll = function() { this.bind('mousewheel DOMMouseScroll', function (e) { var delta = e.wheelDelta || (e.originalEvent && e.originalEvent.wheelDelta) || -e.detail, bottomOverflow = this.scrollTop + $(this).outerHeight() - this.scrollHeight >= 0, topOverflow = this.scrollTop <= 0; if ((delta < 0 && bottomOverflow) || (delta > 0 && topOverflow)) { e.preventDefault(); } }); return this; }; $('.scrollable').isolatedScroll(); A: see if this help you: demo: jsfiddle $('#notscroll').bind('mousewheel', function() { return false }); edit: try this: $("body").delegate("div.scrollable","mouseover mouseout", function(e){ if(e.type === "mouseover"){ $('body').bind('mousewheel',function(){ return false; }); }else if(e.type === "mouseout"){ $('body').bind('mousewheel',function(){ return true; }); } }); A: A less hacky solution, in my opinion is to set overflow hidden on the body when you mouse over the scrollable div. This will prevent the body from scrolling, but an unwanted "jumping" effect will occur. The following solution works around that: jQuery(".scrollable") .mouseenter(function(e) { // get body width now var body_width = jQuery("body").width(); // set overflow hidden on body. this will prevent it scrolling jQuery("body").css("overflow", "hidden"); // get new body width. no scrollbar now, so it will be bigger var new_body_width = jQuery("body").width(); // set the difference between new width and old width as padding to prevent jumps jQuery("body").css("padding-right", (new_body_width - body_width)+"px"); }) .mouseleave(function(e) { jQuery("body").css({ overflow: "auto", padding-right: "0px" }); }) You could make your code smarter if needed. For example, you could test if the body already has a padding and if yes, add the new padding to that. A: In the solution above there is a little mistake regarding Firefox. In Firefox "DOMMouseScroll" event has no e.detail property,to get this property you should write the following 'e.originalEvent.detail'. Here is a working solution for Firefox: $.fn.isolatedScroll = function() { this.on('mousewheel DOMMouseScroll', function (e) { var delta = e.wheelDelta || (e.originalEvent && e.originalEvent.wheelDelta) || -e.originalEvent.detail, bottomOverflow = (this.scrollTop + $(this).outerHeight() - this.scrollHeight) >= 0, topOverflow = this.scrollTop <= 0; if ((delta < 0 && bottomOverflow) || (delta > 0 && topOverflow)) { e.preventDefault(); } }); return this; }; A: here a simple solution without jQuery which does not destroy the browser native scroll (this is: no artificial/ugly scrolling): var scrollable = document.querySelector('.scrollable'); scrollable.addEventListener('wheel', function(event) { var deltaY = event.deltaY; var contentHeight = scrollable.scrollHeight; var visibleHeight = scrollable.offsetHeight; var scrollTop = scrollable.scrollTop; if (scrollTop === 0 && deltaY < 0) event.preventDefault(); else if (visibleHeight + scrollTop === contentHeight && deltaY > 0) event.preventDefault(); }); Live demo: http://jsfiddle.net/ibcaliax/bwmzfmq7/4/ A: Use below CSS property overscroll-behavior: contain; to child element A: I think it's possible to cancel the mousescroll event sometimes: http://jsfiddle.net/rudiedirkx/F8qSq/show/ $elem.on('wheel', function(e) { var d = e.originalEvent.deltaY, dir = d < 0 ? 'up' : 'down', stop = (dir == 'up' && this.scrollTop == 0) || (dir == 'down' && this.scrollTop == this.scrollHeight-this.offsetHeight); stop && e.preventDefault(); }); Inside the event handler, you'll need to know: * *scrolling direction d = e.originalEvent.deltaY, dir = d < 0 ? 'up' : 'down' because a positive number means scrolling down *scroll position scrollTop for top, scrollHeight - scrollTop - offsetHeight for bottom If you're * *scrolling up, and top = 0, or *scrolling down, and bottom = 0, cancel the event: e.preventDefault() (and maybe even e.stopPropagation()). I think it's better to not override the browser's scrolling behaviour. Only cancel it when applicable. It's probablt not perfectly xbrowser, but it can't be very hard. Maybe Mac's dual scroll direction is tricky though... A: Here is my solution I've used in applications. I disabled the body overflow and placed the entire website html inside container div's. The website containers have overflow and therefore the user may scroll the page as expected. I then created a sibling div (#Prevent) with a higher z-index that covers the entire website. Since #Prevent has a higher z-index, it overlaps the website container. When #Prevent is visible the mouse is no longer hovering the website containers, so scrolling isn't possible. You may of course place another div, such as your modal, with a higher z-index than #Prevent in the markup. This allows you to create pop-up windows that don't suffer from scrolling issues. This solution is better because it doesn't hide the scrollbars (jumping affect). It doesn't require event listeners and it's easy to implement. It works in all browsers, although with IE7 & 8 you have to play around (depends on your specific code). html <body> <div id="YourModal" style="display:none;"></div> <div id="Prevent" style="display:none;"></div> <div id="WebsiteContainer"> <div id="Website"> website goes here... </div> </div> </body> css body { overflow: hidden; } #YourModal { z-index:200; /* modal styles here */ } #Prevent { z-index:100; position:absolute; left:0px; height:100%; width:100%; background:transparent; } #WebsiteContainer { z-index:50; overflow:auto; position: absolute; height:100%; width:100%; } #Website { position:relative; } jquery/js function PreventScroll(A) { switch (A) { case 'on': $('#Prevent').show(); break; case 'off': $('#Prevent').hide(); break; } } disable/enable the scroll PreventScroll('on'); // prevent scrolling PreventScroll('off'); // allow scrolling A: Update 2: My solution is based on disabling the browser's native scrolling altogether (when cursor is inside the DIV) and then manually scrolling the DIV with JavaScript (by setting its .scrollTop property). An alternative and IMO better approach would be to only selectively disable the browser's scrolling in order to prevent the page scroll, but not the DIV scroll. Check out Rudie's answer below which demonstrates this solution. Here you go: $( '.scrollable' ).on( 'mousewheel DOMMouseScroll', function ( e ) { var e0 = e.originalEvent, delta = e0.wheelDelta || -e0.detail; this.scrollTop += ( delta < 0 ? 1 : -1 ) * 30; e.preventDefault(); }); Live demo: https://jsbin.com/howojuq/edit?js,output So you manually set the scroll position and then just prevent the default behavior (which would be to scroll the DIV or whole web-page). Update 1: As Chris noted in the comments below, in newer versions of jQuery, the delta information is nested within the .originalEvent object, i.e. jQuery does not expose it in its custom Event object anymore and we have to retrieve it from the native Event object instead. A: I needed to add this event to multiple elements that might have a scrollbar. For the cases where no scrollbar was present, the main scrollbar didn't work as it should. So i made a small change to @Šime code as follows: $( '.scrollable' ).on( 'mousewheel DOMMouseScroll', function ( e ) { if($(this).prop('scrollHeight') > $(this).height()) { var e0 = e.originalEvent, delta = e0.wheelDelta || -e0.detail; this.scrollTop += ( delta < 0 ? 1 : -1 ) * 30; e.preventDefault(); } }); Now, only elements with a scrollbar will prevent the main scroll from begin stopped. A: Pure javascript version of Vidas's answer, el$ is the DOM node of the plane you are scrolling. function onlyScrollElement(event, el$) { var delta = event.wheelDelta || -event.detail; el$.scrollTop += (delta < 0 ? 1 : -1) * 10; event.preventDefault(); } Make sure you dont attach the even multiple times! Here is an example, var ul$ = document.getElementById('yo-list'); // IE9, Chrome, Safari, Opera ul$.removeEventListener('mousewheel', onlyScrollElement); ul$.addEventListener('mousewheel', onlyScrollElement); // Firefox ul$.removeEventListener('DOMMouseScroll', onlyScrollElement); ul$.addEventListener('DOMMouseScroll', onlyScrollElement); Word of caution, the function there needs to be a constant, if you reinitialize the function each time before attaching it, ie. var func = function (...) the removeEventListener will not work. A: You can do this without JavaScript. You can set the style on both divs to position: fixed and overflow-y: auto. You may need to make one of them higher than the other by setting its z-index (if they overlap). Here's a basic example on CodePen. A: Here is the plugin that is useful for preventing parent scroll while scrolling a specific div and has a bunch of options to play with. Check it out here: https://github.com/MohammadYounes/jquery-scrollLock Usage Trigger Scroll Lock via JavaScript: $('#target').scrollLock(); Trigger Scroll Lock via Markup: <!-- HTML --> <div data-scrollLock data-strict='true' data-selector='.child' data-animation='{"top":"top locked","bottom":"bottom locked"}' data-keyboard='{"tabindex":0}' data-unblock='.inner'> ... </div> <!-- JavaScript --> <script type="text/javascript"> $('[data-scrollLock]').scrollLock() </script> View Demo A: All you need is e.preventDefault(); on child element.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600454", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "97" }
Q: Strange Swing compile-time accessibility error Here is the code - import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.SwingUtilities; public final class SetLabelForDemo { public static void main(String[] args){ SwingUtilities.invokeLater(new Runnable(){ @Override public void run() { createAndShowGUI(); } }); } private static void createAndShowGUI(){ final JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(new JLabeledButton("foo:")); // new JLabeledButton("foo:") is the problem frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } private final class JLabeledButton extends JButton{ public JLabeledButton(final String s){ super(); JLabel label = new JLabel(s); label.setLabelFor(this); } } } And here is the error message - No enclosing instance of type SetLabelForDemo is accessible. Must qualify the allocation with an enclosing instance of type SetLabelForDemo (e.g. x.new A() where x is an instance of SetLabelForDemo). I don't understand this error at all. To me, everything seems perfectly valid. Am I missing something? A: You'll have to declare your class JLabeledButton static since you instantiate it within a static context: private static final class JLabeledButton extends JButton { ... } Because your method createAndShowGUI is static the compiler does not know for which instance of SetLabelForDemo you are creating the enclosed class. A: The JLabeledButton class should be static. Else, it can only be instantiated as part of an enclosing SetLabelForDemo instance. A non static inner class must always have an implicit reference to its enclosing instance. A: I know you've accepted an answer, but the other way to solve it is to instantiate the inner class on an instance of the outer class. e.g., private static void createAndShowGUI() { final JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add( new SetLabelForDemo().new JLabeledButton("foo:")); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } This is a funny syntax, but it works. And this has nothing to do with Swing and all to do with use of inner classes inside of a static context. A: Mark JLabeledButton as static class.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600455", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: is it possible for an app to insert an event at a specific date in Facebook Timeline? Is it possible for an app to insert an event at a specific date (in the past) in Facebook Timeline? A: You can publish an action on behalf of a user at a specific point in time by setting the action's "start_time" property to a date in the past. For more info, see: https://developers.facebook.com/docs/beta/opengraph/actions https://developers.facebook.com/docs/beta/opengraph/actions/#timestamps
{ "language": "en", "url": "https://stackoverflow.com/questions/7600456", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Conditional Where statement syntax or some other solution @MallUnit is a parameter with value 'Unit 401,Unit 402,Unit 403' I would like to have a conditional where statement. Assume that before the AND there are other conditions that work just fine. Basically, if ScheduledMallUnitTypeID is null evaluate using the IN condition. Otherwise, use the like clause. AND CASE ScheduledMallUnitTypeID IS NULL THEN ScheduledMallUnitTypeID IN ( SELECT Value FROM Toolbox.dbo.ReportingPortalMultiSetParameterFix(@MallUnit) ) ELSE ScheduledMallUnitTypeID LIKE @MallUnit END A: This would work: WHERE ( ScheduledMallUnitTypeID IS NULL AND ScheduledMallUnitTypeID IN ( SELECT Value FROM Toolbox.dbo.ReportingPortalMultiSetParameterFix(@MallUnit) ) ) OR ( ScheduledMallUnitTypeID IS NOT NULL AND ScheduledMallUnitTypeID LIKE @MallUnit )
{ "language": "en", "url": "https://stackoverflow.com/questions/7600462", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SP2010 Client Object Model 3 MB limit - updating maxReceivedMessageSize doesnt get applied I am using Client Object Model to interact with Sharepoint 2010. When I tried to upload documents greater than 3 MB using Client OM, it gave an error Bad Request. Microsoft suggests this to fix the problem. I tried that and updated the maxReceivedMessageSize property. It works fine after I restart the system, but doesnt get applied to a running sharepoint server. I assume that as the setting might have been kept in memory, so needs an application reset, but I cudnt figure out what to reset. I have tried reseting different Sharepoint services. I have tried reseting Sharepoint website in IIS. Nothing helps. Also, if I set a limit of 10 MB for example, I am able to upload documents around 7.5 MB. I think that is because of additional metadata (content-type properties etc). Is this correct behaviour or I need to change something else as well. Would appreciate any help. Regards. A: I have found this TechNet Forum entry which helped me solve this problem: Tell SharePoint to increase its file size by following the steps below. Ø As the SharePoint Site Administrator, access the SharePoint 2010 Management Shell by 1. On the Start menu, click All Programs. 2. Click Microsoft SharePoint 2010 Products. 3. Click SharePoint 2010 Management Shell. Ø Then run the commands below. get-PSSnapin - Registered Add-PSSnapin Microsoft.SharePoint.Powershell $ws = [Microsoft.SharePoint.Administration.SPWebService]::ContentService $ws.ClientRequestServiceSettings.MaxReceivedMessageSize = 2147483647 $ws.Update() Tell Asp.Net to increase its file size by following the steps below. Ø Edit all web.config files involved to add the element '<httpRuntime>'. When you are done, your addition should look like the example below. Ø 2147483647 bytes is equal to 1.99 GB. <system.web> <httpRuntime useFullyQualifiedRedirectUrl="true" maxRequestLength="2147483647" requestLengthDiskThreshold="2147483647" executionTimeout="18000"/> </system.web> Tell IIS 7.0 and up to increase its file size by following the steps below. Edit all web.config files involved to add the element '<requestLimits>'. When you are done, your addition should look like the example below. <system.webServer> <modules runAllManagedModulesForAllRequests="true"/> <security> <requestFiltering> <requestLimits maxAllowedContentLength="2147483647" /> </requestFiltering> </security> </system.webServer> I hope this helps! A: This is not an issue or hard limit of SharePoint. This is an operational upload limit that is set in place to protect the SharePoint infrastructure. While the operational upload limit is 2 MB, the binary upload limit is 50 MB. There are currently 3 approaches: * *As you have already mentioned, increase the maxReceivedMessageSize. *Use the SaveBinaryDirect methods These methods were introduced starting with SharePoint 2010. It basically uses Distributed Authoring Versioning (DAV) to make a PUT request. Using this approach, you have a 50 MB binary upload limit. Here is an example implementation of approach #2, string siteURL = "https://records.contoso.com"; using (var context = new Microsoft.SharePoint.Client.ClientContext(siteURL)) { context.Credentials = new NetworkCredential( "username", "password", "domain"); string filePathToUpload = "C:\test\test.txt"; context.ExecuteQuery(); using (FileStream fs = new FileStream(filePathToUpload, FileMode.Open) { string targetURL = "/testsite/test.txt"; Microsoft.SharePoint.Client.File.SaveBinaryDirect( context, targetURL, fs, true); } } *If you are using SharePoint 2013 or greater, you can use REST API. The upload limit is 2 GB. A: as per the link you have sent the correct way to get what you need should be something like this: public static void IncreaseMaxReceivedMessageSize () { SPWebService contentService = SPWebService.ContentService; /* Must set this to -1, else, the MaxReceivedMessageSize value for SPWebService.ContentService.WcfServiceSettings["client.svc"] will not be used.*/ contentService.ClientRequestServiceSettings.MaxReceivedMessageSize = -1; // SPWcfServiceSettings has other Properties that you can set. SPWcfServiceSettings csomWcfSettings = new SPWcfServiceSettings(); csomWcfSettings.MaxReceivedMessageSize = 10485760; // 10MB contentService.WcfServiceSettings["client.svc"] = csomWcfSettings; contentService.Update(); } please show your code by editing your question and also explain which system you restart and then it works as opposed as restarting or recycling SP sites where you claim it does not work...
{ "language": "en", "url": "https://stackoverflow.com/questions/7600464", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Regex to validate a string I'm trying to validate a string in an xsd that requires the use of a regex. The string will take the form of the following... JOE~PETE~SAM~BOB and the following are considered valid... JOE ~PETE JOE~SAM~ ~~~BOB JOE~PETE~~ also, each of the names between the ~ can only be a maximum of 6 characters (or digits) and there can only be a maximum of 4 names. The regex I'm trying right now is... [0-9a-zA-Z]{0,6}[~]{0,1}|[0-9a-zA-Z]{0,6}[~]{1}[0-9a-zA-Z]{0,4}[~]{0,1} but am wondering if their is a better solution. NOTE: I should clarify a bit further... if there are only 4 names allowed, that means there would only be 3 ~'s at the most allowed. The tildes denote position, so if ~~~BOB occurred, that would mean the position 1,2, and 3 were empty, and the 4th was occupied by BOB. Also, if the you had JOE~~~, JOE is in the first position, and the rest are empty. Zero or more names could be in any of the 4 positions. Also, symbols like .,*, space, and others are allowed. A: How about this? ^(~*\b[0-9a-zA-Z]{1,6}\b~*){0,4}$ Assuming there is no limit to the number of ~s between, before, and after the names. The \b escape sequence matches "borders" between words - that is, the space between any alphanumeric and any non-alphanumeric character. Also, Pro Tip: the \w escape sequence matches the same thing as [0-9a-zA-Z]. The above regex could be shortened to: ^(~*\b\w{1,6}\b~*){0,4}$ A: i think this is what you're getting at ^[^~]{0,6}(~[^~]{0,6}){0,3}$ A: Are empty strings valid? What about strings consisting solely of tildes? If so, the following will work: ^([0-9a-zA-Z]{0,6}~?){0,4}$
{ "language": "en", "url": "https://stackoverflow.com/questions/7600471", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Auditing HttpInvoker invactions The server, a stand-alone SE application running Spring 2.5.6 and an embedded jetty. Clients, Swing application, connects to the server using HttpInvoker. There are a lot of services exposed by the server and now, new requirements have emerged saying I need to log (almost) every invocation made by the client. What I would like to to do is for the client to send some extra information, (username, workstationId etc. Strings and ints). A typical method on the server would look like this public void doStuff(int someParam) { // Do stuff List result = method(someParam) // Audit // get the client information from somewhere?!! String username; int workstationId; auditDao.doStuffPerformed(username, workstationId, someParam, result); } So, how do I get the client information from within a method on the server. One solution that I've tried is to add client information as request attributes and call method RequestContextHolder.getRequestAttributes(); from within method. I have added a CommonsHttpInvokerRequestExecutor on the client side and overloaded the following method in order to add the additional information. @Override protected PostMethod createPostMethod(HttpInvokerClientConfiguration config) throws IOException { PostMethod postMethod = super.createPostMethod(config); postMethod.addRequestHeader("someHeader", "someHeader2"); postMethod.addParameter("someParam", "someParam2"); postMethod.setRequestHeader("someRequestHeader", "someRequestHeader2"); return postMethod; } This will however not work. The headers or parameters are not accessible on the server. Any response would be greatly appreciated. A: I think you're on the right track. You should just use a custom SimpleHttpInvokerServiceExporter subclass on the server-side, and override readRemoteInvocation to extract the headers set by the client from the HttpExchange argument. These header values could be stored in a static ThreadLocal session variable, which would be accessible anywhere in the server-side code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600472", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Server timeout issue when getting a large amount (500000) of records from a SharePoint 2010 list I am working in SharePoint 2010, I want to get 500000 "Announcement" list items from the current spweb. I have a server timeout issue and the code is given below. SPList list = web.Lists["Announcements"]; SPQuery query= new SPQuery(); query.Query = "<Where><And><Geq><FieldRef Name=\"ID\" /><Value Type=\"Counter\"> 1</Value></Geq><Leq><FieldRef Name=\"ID\" /><Value Type=\"Counter\">500000 </Value></Leq></And></Where>"; query.RowLimit = 500000; SPListItemCollection items = list.GetItems(query); DataTable dt = items.GetDataTable(); //Here I get the timeout error. How do I resolve this issue? A: SharePoint's best practices clearly state that no more than about 2000 rows should be in a view. Best Practices also state that pulling list items programatically should be limited to about 10,000 rows at a time. Here is a good article to help set reasonable limits for lists: http://sharepointsearch.com/cs/blogs/notorioustech/archive/2009/04/08/best-practices-for-large-sharepoint-lists-and-documents-libraries.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7600474", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to prevent specific comma delimted values being parsed (C#) Possible Duplicate: Dealing with commas in a CSV file I am currently parsing values from a CSV file and adding them to a datatable. The csv file contains 5 columns and am parsing each row before adding it to the datatable. After parsing the csv, the datatable could be visualized as the following: | Town/City | Cost | | Birmingham | 400 | | Manchester | 500 | For this data, there are no problems. However, I have some values that look like the following: | Town/City | Cost | | London, West | 800 | As there is a comma between a value for the one column, it is obviously parsing this as a seperate column. The data cannot be changed, therefore I need a way to parse this as a single column rather than two. This is my code so far that parses rows which have 5 columns. I have commented the bit where I guess the new code will need to go. //parse csv file and return as data table public System.Data.DataTable GetCsvData() { string strLine; char[] charArray = new char[] { ',' }; List<string> strList = new List<string>(); System.Data.DataTable dt = new System.Data.DataTable("csvData"); System.IO.FileStream fileStream = null; System.IO.StreamReader streamReader = null; if (!string.IsNullOrEmpty(csvFilePath)) { fileStream = new System.IO.FileStream(csvFilePath, System.IO.FileMode.Open); streamReader = new System.IO.StreamReader(fileStream); strLine = streamReader.ReadLine(); strList = strLine.Split(charArray).ToList(); //only add first 5 columns for (int i = 0; i <= 4; i++) dt.Columns.Add(strList[i].Trim()); strLine = streamReader.ReadLine(); while (strLine != null) { strList = strLine.Split(charArray).ToList(); System.Data.DataRow dataRow = dt.NewRow(); /*THIS CODE PARSES THE ROW'S 5 COLUMNS AND NEEDS TO PARSE COMMA SEPERATED VALUES AS A SINGLE VALUE*/ for (int i = 0; i <= 4; i++) dataRow[i] = strList[i].Trim(); dt.Rows.Add(dataRow); strLine = streamReader.ReadLine(); } streamReader.Close(); return dt; } return null; } Any help with this would be greatly appreciated as I am struggling to find answers on google. A: I propose checking the array after the split. If you find it has N + 1 columns (where you expect N), merge the two City columns and shift the others down (strList[i] = strList[i+1]). Otherwise process as normal. Of course this only works if you have only the one column that has a potential comma. A: In addition to just checking the length of the split array as @Bahri suggests, if your data is predictable enough (as in your example), you could check column content. If cost in your example is always a number, you could check to see if it contains only digits (or use a Regex for more complex matching). If not, then collapse the previous two columns.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600477", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ASP.Net MVC3: Set up Routing to handle multiple unique ID's? I'm building an MVC application that consists of entities that can be referenced by two different unique ID's, an ugly system generated ID, and a more user-friendly 5 character "Short Code". For example, I would like my end-users to be able to type the following url's in their browsers: http://intranet/PRJ2011004 http://intranet/DEP42 Again, both codes are unique. I have the routing for the first URL correctly set up. When the user enters that URL, they receive the proper page displaying the index page for the entity: PRJ201104. How do I set up the route to handle the second scenario? Preferably there is a way to "trick" MVC into changing the value it passes to the controller from the short code to the project. I would like a way to intercept the 5 character short code route, take the value provided and look it up in my entities table, then if I find a matching record I would like to either (in order of preference): * *Display the entities' index page while still retaining the short code in the url. In this scenario, I would like to "trick" the controller handling the route into thinking the "id" passed in is actually the unique ID and not the short code (in order to not have to refactor my existing code) *Re-direct the url to the one with the working unique (ugly) ID. And if I don't find a matching Entity using that short code value I would let my standard route handling continue (so, for example, my "Error" and "Admin" controllers, which are both 5 characters as well but not Short Codes, will continue to work appropriately). TIA A: A custom route could do the job: public class MyRoute : Route { public MyRoute(string url, object defaults) : base(url, new RouteValueDictionary(defaults), new MvcRouteHandler()) { } public override RouteData GetRouteData(HttpContextBase httpContext) { var rd = base.GetRouteData(httpContext); var id = rd.Values["id"] as string; if (id == null) { return rd; } // TODO: if you think that the id provided is a pretty id // query the database to fetch the other id if (IsPrettyId(id)) { id = FetchCorrespondingId(id); rd.Values["id"] = id; } return rd; } } and then register this custom route: public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.Add( "Default", new MyRoute( "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional } ) ); } Now inside the controller action you will always have the long ugly id: public ActionResult Index(string id) { }
{ "language": "en", "url": "https://stackoverflow.com/questions/7600479", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Any windows API to let me re-log in a "locked" windows 7? I've built a program running on windows 7 to communicate with a usb device "power mate". When I leave my computer, I always press "WIN+L" to lock my computer, and when I get back, I press "CTRL+ALT+DEL" and enter my password to log in the computer. At the same time, the program is running. I'm wondering is there any windows API or something to let me use the usb device to log in the computer? (there is a button on the usb device you can push) UPDATE: Thanks guys. It's just an idea when I looked my usb device and asked myself "what can I do for this little guy?". It's supposed to be fun hobby project and I'm curious to see if it's possible. The usb device is connected to the computer all the time. And in reality, the usb device can do more than just pushing a button (the product name is "griffin powermate"). My intention is to do some custom action to unlock my computer, such as left rotate 3 turns and push a button 2 times. Anyway, this is really not meant to be a solution with strong security. A: You can use the OS's log on provider API (GINA for pre-vista and credential provider for vista and onward) to use your USB device as an alternative credential instead of user name/password. You also need a driver for the device that can talk to your log on provider and trigger a log on request when a button is pushed. You can use Windows Vista's smart card architecture as a reference. A: You could possibly write a credential provider to do this but why? This would effectively give credential free access to your computer. If you want to do that then don't bother locking it in the first place.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600481", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: jQuery and Restful WebServices Security I have a project with the following aspects: * *Frontend web application made in PHP, jQuery (Ajax) with a local database for aspects like end users authetication and configuration of the frontend web application. *Backend REST Web Services (running in other domain and machine than frontend application), invoked by the frontend using jQuery and JSONP technique. I need make that communication in a secure way and I don't know how. I hope someone can help me. I'll be very very grateful. A: The easiest thing to do is to serve the Web Services through HTTPS and use HTTP Basic as the authentication method. This is simple to set up on both the client and server and supported by most front- and back-end frameworks. If your web browser can speak HTTPS, Ajax (i.e. XMLHttpRequest) can speak HTTPS too. You can easily set the Authorization header in the Ajax requests, and the value can be built by just base-64 encoding a username and password retrieved from the user of the web application. A: There is no simple answer for this, however there a few methods that you can choose to employ based on your specific needs. * *To secure web services you can authenticate requests using OAuth. *Never trust input to the server, sanitize everything. Details here. *Microsoft offers a generalized (eg. not Microsoft product-based) guide for building secure applications here. Good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/7600486", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Inner classes with method names and different signatures than the outer class I know how to get this code to work, but I'm curious why the compiler is not able to figure out that the call is to the outer class method: public class Example { public void doSomething(int a, int b) { } public class Request { public int a; public int b; public void doSomething() { doSomething(a,b); // Error. Fix: Example.this.doSomething(a,b); } } } Is there a deeper design reason for this than protecting coders from making mistakes? A: By the language definition, the outer-class method is not visible in the inner class because it is shadowed. Shadowing is based on name rather than signature. This is a good thing. Consider the alternative. You could hide a subset of method overloads. Someone else could try to change the arguments in a call, to call one of the other overloaded methods. Simply changing the arguments could cause the recipient object to change. This would be surprising, and could cost time to debug. From the Java Language Specification, 6.3.1: Some declarations may be shadowed in part of their scope by another declaration of the same name, in which case a simple name cannot be used to refer to the declared entity. A declaration d of a type named n shadows the declarations of any other types named n that are in scope at the point where d occurs throughout the scope of d. ... A declaration d is said to be visible at point p in a program if the scope of d includes p, and d is not shadowed by any other declaration at p. When the program point we are discussing is clear from context, we will often simply say that a declaration is visible. A: This will work : public class Example { public void doSomething(final int a, final int b) { } public class Request { public int a; public int b; public void foo() { doSomething(a, b); // Error. Fix: Example.this.doSomething(a,b); } } } You have a namespace collision on the function name doSomething, hence the need to qualify. A: Inner classes do not by default inherit from their corresponding outer class.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600497", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: When hover too fast between elements, double elements show When I hover between elements very quickly, two or more elements will show. If move slowly, it works perfect. Here's the code: $("#services_menu a").hover(function(e) { var id = this.hash; $("#services_description div:visible").not(id).fadeOut('fast', function(){ $(id).fadeIn(); }); e.preventDefault(); }); $("#services_description div:not(#agency_leasing)").hide(); How do I fix this? Thanks. A: Just put .stop(true,true) before fadeOut and fadeIn
{ "language": "en", "url": "https://stackoverflow.com/questions/7600500", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javascript loop json for value and apply if condition met If I had the following JSON, [{},{"param":"#content","value":"K2-12M","quantity":1,"q_id":3,"clear":1} {"param":"#content","value":"K2-12F","quantity":2,"q_id":3,"clear":0}] In js/jquery, how would I loop through, and if any of the items have "clear":0, then set ALL items to "clear":0 ? A: var clear; for( var i=0, l=json.length; i<l; i++ ){ if( 0 === json[i].clear ){ clear = true; break; } } if( clear ){ for( i=0; i<l; i++) { json[i].clear = 0; } } or using jQuery (this is less efficient): $( json ).filter( function( ix, obj ){ return 0 === obj.clear; } ).length && $( json ).each( function( ix, obj ){ obj.clear = 0; } ); A: Nested for-loop: for(var i = 0, l = json.length; i < l; i++ ){ if(json[i].clear == 0){ for(var x = 0; x < l; x++) { json[x].clear = 0; } break; } } Fiddle for your fiddling pleasure.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600505", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Effect of TCP_CORK I'm having a use case where I'm sending data via TCP/IP in one direction. I'm doing this via multiple send()-calls with very small (in relation to the size of an ethernet frame) payloads (without any flags for the send()-call). To prevent bloating up my small payload packets to the size of a full ethernet frame, I thought it would be nice to use the TCP_CORK socket option. This works, but when actually comparing the situation before and after using TCP_CORK, I noticed that this kind of aggregation was already done. Why is this so? As I said, I do not use any flags for send() (like MSG_MORE) or other socket options, so I would have expected my original solution to be wasteful. A: If you are sending messages very quickly you may be seeing the Nagle algorithm at work. You have to disable it explicitly. Iirc in linux you have to set TCP_NODELAY, but there are different options in other operating systems.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600507", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What HTTP header should a REST client pass for the IP Address of a web client? I am developing a web service that another group is developing a web front end against. My web service needs to do some IP Address logging of the web client, so I need the web front end to pass me the IP Address of the actual user in a HTTP header. My original thought was to use X-Forwarded-For, but that did not feel completely correct, is there a better header for this? Note: The REST client is trusted and authenticated, so I am not worry about a malicious client spoofing the source address. A: I think X-Forwarded-For sounds like the perfect header for your use-case. It's supported by many proxy servers and although it's not ratified in an RFC, the problem it solves is so small that there's little chance of interoperability problems. Why don't you want to use it?
{ "language": "en", "url": "https://stackoverflow.com/questions/7600510", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Css asp:menu floating I'm having an issue with CSS (not sure). Actually I'm new to CSS, and I'm trying to understand it. Ok, let's take a look: * *I've created an WebApplication (ASP.Net web) with Visual Studio 2010 *And I decided to use the original template given by VS 2010 *I've tried to make the default menu right floating. But I couldn't make that. *The original menu looks like: |Home|About_______________________________| *And I want to make it looks like: |_______________________________Home|About| *I tried style="float: right;". *I also tried dir="rtl", but I got something like: |_______________________________About|Home| How can I solve this problem? I'm not sure that it's a CSS issue or a control issue. I'm not familiar with Web Application, I've worked on Winform Application. This is the Site.Master: <%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="WebApplication1.SiteMaster" %> <!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" xml:lang="en"> <head runat="server"> <title></title> <link href="~/Styles/Site.css" rel="stylesheet" type="text/css" /> <asp:ContentPlaceHolder ID="HeadContent" runat="server"> </asp:ContentPlaceHolder> </head> <body> <form runat="server"> <div class="page"> <div class="header"> <div class="title"> <h1> My ASP.NET Application </h1> </div> <div class="loginDisplay"> <asp:LoginView ID="HeadLoginView" runat="server" EnableViewState="false"> <AnonymousTemplate> [ <a href="~/Account/Login.aspx" id="HeadLoginStatus" runat="server">Log In</a> ] </AnonymousTemplate> <LoggedInTemplate> Welcome <span class="bold"> <asp:LoginName ID="HeadLoginName" runat="server" /> </span>! [ <asp:LoginStatus ID="HeadLoginStatus" runat="server" LogoutAction="Redirect" LogoutText="Log Out" LogoutPageUrl="~/" /> ] </LoggedInTemplate> </asp:LoginView> </div> <div class="clear hideSkiplink"> <asp:Menu ID="NavigationMenu" runat="server" CssClass="menu" EnableViewState="false" IncludeStyleBlock="false" Orientation="Horizontal" dir="rtl"> <Items> <asp:MenuItem NavigateUrl="~/Default.aspx" Text="Home" /> <asp:MenuItem NavigateUrl="~/About.aspx" Text="About" /> </Items> </asp:Menu> </div> </div> <div class="main"> <asp:ContentPlaceHolder ID="MainContent" runat="server" /> </div> <div class="clear"> </div> </div> <div class="footer"> </div> </form> </body> </html> and this is the CSS: /* DEFAULTS ----------------------------------------------------------*/ body { background: #b6b7bc; font-size: .80em; font-family: "Helvetica Neue", "Lucida Grande", "Segoe UI", Arial, Helvetica, Verdana, sans-serif; margin: 0px; padding: 0px; color: #696969; } a:link, a:visited { color: #034af3; } a:hover { color: #1d60ff; text-decoration: none; } a:active { color: #034af3; } p { margin-bottom: 10px; line-height: 1.6em; } /* HEADINGS ----------------------------------------------------------*/ h1, h2, h3, h4, h5, h6 { font-size: 1.5em; color: #666666; font-variant: small-caps; text-transform: none; font-weight: 200; margin-bottom: 0px; } h1 { font-size: 1.6em; padding-bottom: 0px; margin-bottom: 0px; } h2 { font-size: 1.5em; font-weight: 600; } h3 { font-size: 1.2em; } h4 { font-size: 1.1em; } h5, h6 { font-size: 1em; } /* this rule styles <h1> and <h2> tags that are the first child of the left and right table columns */ .rightColumn > h1, .rightColumn > h2, .leftColumn > h1, .leftColumn > h2 { margin-top: 0px; } /* PRIMARY LAYOUT ELEMENTS ----------------------------------------------------------*/ .page { width: 960px; background-color: #fff; margin: 20px auto 0px auto; border: 1px solid #496077; } .header { position: relative; margin: 0px; padding: 0px; background: #4b6c9e; width: 100%; } .header h1 { font-weight: 700; margin: 0px; padding: 0px 0px 0px 20px; color: #f9f9f9; border: none; line-height: 2em; font-size: 2em; } .main { padding: 0px 12px; margin: 12px 8px 8px 8px; min-height: 420px; } .leftCol { padding: 6px 0px; margin: 12px 8px 8px 8px; width: 200px; min-height: 200px; } .footer { color: #4e5766; padding: 8px 0px 0px 0px; margin: 0px auto; text-align: center; line-height: normal; } /* TAB MENU ----------------------------------------------------------*/ div.hideSkiplink { background-color:#3a4f63; width:100%; } div.menu { padding: 4px 0px 4px 8px; } div.menu ul { list-style: none; margin: 0px; padding: 0px; width: auto; } div.menu ul li a, div.menu ul li a:visited { background-color: #465c71; border: 1px #4e667d solid; color: #dde4ec; display: block; line-height: 1.35em; padding: 4px 20px; text-decoration: none; white-space: nowrap; } div.menu ul li a:hover { background-color: #bfcbd6; color: #465c71; text-decoration: none; } div.menu ul li a:active { background-color: #465c71; color: #cfdbe6; text-decoration: none; } /* FORM ELEMENTS ----------------------------------------------------------*/ fieldset { margin: 1em 0px; padding: 1em; border: 1px solid #ccc; } fieldset p { margin: 2px 12px 10px 10px; } fieldset.login label, fieldset.register label, fieldset.changePassword label { display: block; } fieldset label.inline { display: inline; } legend { font-size: 1.1em; font-weight: 600; padding: 2px 4px 8px 4px; } input.textEntry { width: 320px; border: 1px solid #ccc; } input.passwordEntry { width: 320px; border: 1px solid #ccc; } div.accountInfo { width: 42%; } /* MISC ----------------------------------------------------------*/ .clear { clear: both; } .title { display: block; float: left; text-align: left; width: auto; } .loginDisplay { font-size: 1.1em; display: block; text-align: right; padding: 10px; color: White; } .loginDisplay a:link { color: white; } .loginDisplay a:visited { color: white; } .loginDisplay a:hover { color: white; } .failureNotification { font-size: 1.2em; color: Red; } .bold { font-weight: bold; } .submitButton { text-align: right; padding-right: 10px; } All codes above are the default codes given by VS 2010. Help me! Thanks alot! A: Oh, I've found something, just edit the div.menu class: div.menu { padding: 4px 8px 4px 0px; float: right !important } The "!important" keyword (I'm not sure about this strange thing), make the browser render my asp:menu float style based on my css class not from the generated javascript. I found it here: http://walaapoints.blogspot.com/2011/04/aspnet-menu-rtl.html A: If this is your menu div.menu ul { list-style: none; margin: 0px; padding: 0px; width: auto; } then you need to add a width to it in order to make it float. So something like div.menu ul { list-style: none; margin: 0px; padding: 0px; width: 300px; //CHANGE THIS float:right; } The width needs to be something less than 100%/auto for it to float properly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600516", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: When Deploying MVC 3 Application to IIS 7 The index pages load fine but when I select Menu item 404 Error Pops I have BIN deployed my MVC 3 application to my local IIS7 server. It runs fine in Visual Basic. But in IIS 7 only the index pages for my views are accessible. If I select any menu item it throws this error: Server Error in '/' Application The Resource cannot be found Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavalible. Please review the following URL and make sure that it is spelled correctly. Requested URL: /Admin/import_excel.vbhtml Version Information: Microsoft.NET Framework Version 4.0.30319; ASP.NET Version 4.0.30319.237 Below is a copy of the routing table that is being used as well.... Public Class MvcApplication Inherits System.Web.HttpApplication Shared Sub RegisterGlobalFilters(ByVal filters As GlobalFilterCollection) filters.Add(New HandleErrorAttribute()) End Sub Shared Sub RegisterRoutes(ByVal routes As RouteCollection) routes.IgnoreRoute("{resource}.axd/{*pathInfo}") ' MapRoute takes the following parameters, in order: ' (1) Route name ' (2) URL with parameters ' (3) Parameter defaults routes.MapRoute( _ "Default", _ "{controller}/{action}/{id}", _ New With {.controller = "Home", .action = "Index", .id = UrlParameter.Optional} _ ) End Sub Sub Application_Start() AreaRegistration.RegisterAllAreas() RegisterGlobalFilters(GlobalFilters.Filters) RegisterRoutes(RouteTable.Routes) End Sub End Class Anyone know where I might be going wrong at????? A: figured out what was wrong... I had a problem with Microsoft.ACE not being registered on the server machine. I found a thread in a forum that said to change the Target Cpu to x86. Later I found that I just needed to download the ace data assemblies but never changed the Target CPU back to ANY. After changing it back I recompiled and deployed it again with no problems... Although I am still lost as to why this would cause only 404's on some pages and not all....
{ "language": "en", "url": "https://stackoverflow.com/questions/7600517", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HTTPS WCF Basic HttpBindings getting HTTP 403 I have an HTTPS webserver on WCF hosted under IIS 7.5. I have set the SSL settings to require SSL and ignore client certificates. When I try to add the web reference in Visual Studio, I get the following error. How do I fix this problem? I can see that it's trying to request ?disco using HTTP instead of HTTPS. I think this is the problem, but I am not sure how to address this. The document at the url https://testserver/service1.svc?wsdl was not recognized as a known document type. The error message from each known type may help you fix the problem: - Report from 'DISCO Document' is 'There was an error downloading 'http://testserver/service1.svc?disco'.'. - The request failed with HTTP status 403: Forbidden. - Report from 'WSDL Document' is 'The document format is not recognized (the content type is 'text/html; charset=UTF-8').'. - Report from 'XML Schema' is 'The document format is not recognized (the content type is 'text/html; charset=UTF-8').'. - Report from 'https://testserver/service1.svc?wsdl' is 'The document format is not recognized (the content type is 'text/html; charset=UTF-8').'. A: Since you're able to get the WSDL through your web browser, a possible issue might be with hosting the service in IIS and configuring site bindings. It was a known issue on the forums some time ago, check out these links: * *Problem in consuming hosted WCF service *HOWTO: Fix WCF Host Name on IIS Good luck! A: I had to disable Require SSL to get it to work. I am not sure why disco goes to do an HTTP when the WSDL URL you provide is HTTPS.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600519", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Error Displaying Facebook Social Plugins Im having problems using the Facebook social plugins. If its important, I use GWT to display the code inside an HTML widjet I put this in my html <script> (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/all.js#xfbml=1"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); </script> <fb:comments width="600" num_posts="2" href="http://www.woojah.com"></fb:comments> And nothing is displayed. However, if I open the source code with firebug, and I cut that code and paste it again, it is displayed. It is as if that code needs a special "refreshing" or "reloading". By the way, I got that code from the developers.facebook.com page. It's the social plugin comment code. Also my html tag is <html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="https://www.facebook.com/2008/fbml"> So my question is: Does anyone know why the comment plugin is not displayed and why, when I cut and paste the exact same code with firebug it is displayed. A: You may want to look into using the FB.XFBML.parse() command to have the SDK reparse the page after you use GWT to insert the code inside your widget.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600521", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Java: Should I / What to throw when authentication is excepted? I am writing a small library, and in which I need to access several different type of files. While the access method itself is different for each kind of file format, they seem to have a lot in common, and I put an interface in the class hierarchy, in which I wrote a method that should connect to the data source. However, since the data source might be protected by password and/or user permission, sometimes it need authentication to retrieve the data. My questions are: * *It is a good idea to throw an exception when authentication is required? Since I want to expose the implementation as little as possible, I only want to tell the user what happened. But authentication might need many different things (username, password, etc.), so could I pack them into one exception and throw it out? Or, maybe there is a better way without resorting to exceptions, since "Authentication required" is not really the exceptional behavior that exception usually used to handle. *What exception to throw when authentication is required? Now suppose I decided to use exception to handle this. Which exception should I throw? The several AuthenticationExceptions shipped with Java API does not seem to fit this requirement since they all seem to be very case specific, e.g., used in the naming service. I am not sure if SecurityException is the way to go, but if this is improper, I still really do not want to throw my own exception, since that will impede other people to understand my code and what is going on behind the API. Thanks for any input! This is somewhat lengthy or maybe too verbose, so any edits that would improve the question is extremely welcomed. A: AuthenticationException I would go for throwing AuthenticationException with the message either if the login is needed and username or password wrong if the pass is not good. It is a best practice to do not disclose whether login exists. And sometimes in HTTP it is common to hide unauthorized access with a not found. So if the credentials do not allow to connect it is like the connection does not exist. A: Since it's your own API, you might create your own Exception to go with it, which can carry the details... There's no requirement or benefit to using the Java exception that "sounds closest to" your exception. I personally find that peppering my code with try/catch blocks is... tedious and unsightly. So I try to make API's that don't require it. In your case, maybe you could provide queries so your API clients could preflight the actions, and their usage might look something like: Thing t = new Thing(...); if(t.needsAuth()) { boolean ok = t.doPassword("abc123"); if(!ok) log("wrong password"); } boolean did= t.doIt(); if(!did) log("sorry: " + t.getProblem());
{ "language": "en", "url": "https://stackoverflow.com/questions/7600522", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Draw background image in gtk - none of my attempts work I've been trying to set a background image on a gtk widget without success, even after trying 4 different approaches. The following program contains 3 approaches (the 4th approach involves no code). I compiled it using MinGW (g++ 4.5.0) and gtkmm 2.4. The APPROACH macro can be set to 1, 2 or 3 in order to choose which approach to compile. I've also added references in the comments, so you can find out where I got the ideas from. #include <iostream> #include <gtkmm/main.h> #include <gtkmm/alignment.h> #include <gtkmm/box.h> #include <gtkmm/entry.h> #include <gtkmm/eventbox.h> #include <gtkmm/frame.h> #include <gtkmm/image.h> #include <gtkmm/label.h> #include <gtkmm/table.h> #include <gtkmm/window.h> // Set this to 1, 2 or 3 to try different ways of drawing the background // Set to 0 to load no background at all #define APPROACH (0) // Making this alignment global in order to modify it from drawBackground Gtk::Alignment* alignment; bool drawBackground(GdkEventExpose* event) { std::cout << "Draw background" << std::endl; // Load background image Glib::RefPtr<Gdk::Pixbuf> pixbuf = Gdk::Pixbuf::create_from_file("background.jpg"); Glib::RefPtr<Gdk::Pixmap> pixmap; Glib::RefPtr<Gdk::Bitmap> mask; pixbuf->render_pixmap_and_mask(pixmap, mask,0); { // Test that pixbuf was created correctly Glib::RefPtr<Gdk::Pixbuf> back_to_pixbuf = Gdk::Pixbuf::create((Glib::RefPtr<Gdk::Drawable>)pixmap, 0, 0, pixbuf->get_width(), pixbuf->get_height()); back_to_pixbuf->save("back_to_pixbuf.png", "png"); } #if APPROACH == 1 // Approach 1: draw_pixbuf // Ref: http://islascruz.org/html/index.php/blog/show/Image-as-background-in-a-Gtk-Application..html Glib::RefPtr<Gtk::Style> style = alignment->get_style(); alignment->get_window()->draw_pixbuf(style->get_bg_gc(Gtk::STATE_NORMAL), pixbuf, 0, 0, 0, 200, pixbuf->get_width(), pixbuf->get_height(), Gdk::RGB_DITHER_NONE, 0, 0); #endif #if APPROACH == 2 // Approach 2: set_back_pixmap // Ref: http://www.gtkforums.com/viewtopic.php?t=446 // http://stackoverflow.com/questions/3150706/gtk-drawing-set-background-image alignment->get_window()->set_back_pixmap(pixmap); #endif } int main (int argc, char *argv[]) { Gtk::Main kit(argc, argv); Gtk::Window w; Gtk::VBox mainBox; // Top image Gtk::Image topImage("header.jpg"); mainBox.pack_start(topImage,false,false,0); // Middle alignment alignment = Gtk::manage(new Gtk::Alignment); mainBox.pack_start(*alignment,true,true,0); // Create widget Gtk::Alignment mywidget(0.5, 0.5, 0.1, 0.9); Gtk::Table table; Gtk::Label label1("Username"); table.attach(label1,0,1,0,1); Gtk::Label label2("Password"); table.attach(label2,0,1,1,2); Gtk::Entry entry1; table.attach(entry1,1,2,0,1); Gtk::Entry entry2; table.attach(entry2,1,2,1,2); Gtk::Button button("Login"); table.attach(button,1,2,2,3); mywidget.add(table); // Put widget in middle alignment alignment->add(mywidget); // Try to change the background #if APPROACH == 1 || APPROACH == 2 alignment->signal_expose_event().connect(sigc::ptr_fun(&drawBackground), true); #endif #if APPROACH == 3 // Approach 3: modify the style using code // Ref: http://www.gtkforums.com/viewtopic.php?t=446 // Load background image Glib::RefPtr<Gdk::Pixbuf> pixbuf = Gdk::Pixbuf::create_from_file("background.jpg"); Glib::RefPtr<Gdk::Pixmap> pixmap; Glib::RefPtr<Gdk::Bitmap> mask; pixbuf->render_pixmap_and_mask(pixmap, mask,0); Glib::RefPtr<Gtk::Style> style = alignment->get_style()->copy(); style->set_bg_pixmap(Gtk::STATE_NORMAL,pixmap); style->set_bg_pixmap(Gtk::STATE_ACTIVE,pixmap); style->set_bg_pixmap(Gtk::STATE_PRELIGHT,pixmap); style->set_bg_pixmap(Gtk::STATE_SELECTED,pixmap); style->set_bg_pixmap(Gtk::STATE_INSENSITIVE,pixmap); alignment->set_style(style); #endif // Approach 4: modify share\themes\MS-Windows\gtk-2.0 // adding the following line // bg_pixmap[NORMAL] = "D:\\path\\to\\file\\background.jpg" // in the style "msw-default" section // Ref: http://lists.ximian.com/pipermail/gtk-sharp-list/2005-August/006324.html // Show the window w.add(mainBox); w.show_all(); kit.run(w); return 0; } Links to images I used: header.jpg background.jpg The layout mimics that of my actual program. The main window contains a Gtk::VBox with a header image on top and an Gtk::Alignment at the bottom. The contents of this alignment will change over time but I want it to have a background image always visible. When loading no background at all, the header image loads correctly and the window looks like this: Approach 1 is the one that is closer to work, though it hides the labels and the buttons: Approaches 2 and 3 look the same as loading no background. Besides, approach 2 gives me the following error message: (test-img-fondo.exe:1752): Gdk-CRITICAL **: gdk_window_set_back_pixmap: assertion `pixmap == NULL || !parent_relative' failed Finally, in approach 4, I attempt to modify share\themes\MS-Windows\gtk-2.0 by adding the following line bg_pixmap[NORMAL] = "D:\\path\\to\\file\\background.jpg" in the style "msw-default" section. It doesn't work either. So, has anyone succesfully drawn a background image on a Gtk widget? Is this possible at all? Any changes in my code that would make this work? Any workarounds? All help is greatly appreciated. A: I think I've solved it myself. Use approach 1 but change this line alignment->signal_expose_event().connect(sigc::ptr_fun(&drawBackground), true); for this: alignment->signal_expose_event().connect(sigc::ptr_fun(&drawBackground), false); This way, the call to drawBackground occurs before gtk calls its own handlers. I should also point out that, in a real program, the images should be loaded once outside of drawBackground.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600523", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: trying to track down a Memory Leak using open CV and SDL The program main loop below is where I am having troubles finding a memory leak. I run Top and every time I loop through taking a picture and printing it, I lose memory that is never recovered even upon exit. I have run valgrind and some results are at the bottom. The progam runs fine until it runs out of memory. I seem to have leaks with cups and opencv and the leak is not a couple hundred bytes it is significant - I appreciate any help Ubuntu 11.04 opencv 2.3.1 void DrawImage(SDL_Surface *srcimg, int sx, int sy, int sw, int sh, SDL_Surface *dstimg, int dx, int dy, int alpha) { if ((!srcimg) || (alpha == 0)) return; //If theres no image, or its 100% transparent. SDL_Rect src, dst; src.x = sx; src.y = sy; src.w = sw; src.h = sh; dst.x = dx; dst.y = dy; dst.w = src.w; dst.h = src.h; SDL_BlitSurface(srcimg, &src, dstimg, &dst); } // ************************ Start of Main Loop ************************ while(Leave == 0) { if(Start != 0) { atr = IMG_Load("pic1.jpg"); DrawImage(atr, 0,0,DSP_WIDTH,DSP_HEIGHT,screen, 0, 0, 255); SDL_Flip(screen); CvCapture *camera = cvCreateCameraCapture(-1); IplImage *frame2; SDL_Surface* surface = NULL; cvSetCaptureProperty(camera, CV_CAP_PROP_FRAME_HEIGHT, IMG_HEIGHT); cvSetCaptureProperty(camera, CV_CAP_PROP_FRAME_WIDTH, IMG_WIDTH); surface = IMG_Load("background.jpg"); Seconds = 15; while(Seconds !=0) { frame2 = cvQueryFrame(camera); if(!frame2)continue; //Couldn't get an image, try again next time. SDL_Surface* surface2 = NULL; surface2 = SDL_CreateRGBSurfaceFrom((void*)frame2->imageData, frame2->width, frame2->height, frame2->depth*frame2->nChannels, frame2->widthStep, 0xff0000, 0x00ff00, 0x0000ff, 0); SDL_BlitSurface(surface2, NULL, surface, &offsetpic); SDL_FreeSurface(surface2); DrawImage(surface, 0,0,DSP_WIDTH,DSP_HEIGHT,screen, 0, 0, 255); SDL_Flip(screen); } if(!cvSaveImage("lastprint.jpg",frame2,0)) printf("Could not save: lastprint.jpg"); cvReleaseImage(&frame2); cvReleaseCapture(&camera); //Release the camera capture structure. SDL_FreeSurface(surface); cupsPrintFile(dest->name, "lastprint.jpg", "JOB1", dest->num_options, dest->options); if(Start !=0) Start--; // Dec Start // atr = IMG_Load("pic1.jpg"); DrawImage(atr, 0,0,DSP_WIDTH,DSP_HEIGHT,screen, 0, 0, 255); SDL_Flip(screen); } } Many of the one directly below here vvvvv 32,780 bytes in 1 blocks are still reachable in loss record 180 of 182 at 0x4026864: malloc (vg_replace_malloc.c:236) by 0x4365BA7: ??? (in /usr/lib/libcups.so.2) by 0x436731E: ippReadIO (in /usr/lib/libcups.so.2) by 0x436785C: ippReadIO (in /usr/lib/libcups.so.2) by 0x436785C: ippReadIO (in /usr/lib/libcups.so.2) by 0x4367E85: ippRead (in /usr/lib/libcups.so.2) by 0x437A173: cupsGetResponse (in /usr/lib/libcups.so.2) by 0x437A501: cupsDoIORequest (in /usr/lib/libcups.so.2) by 0x437A6FA: cupsDoRequest (in /usr/lib/libcups.so.2) by 0x4358386: ??? (in /usr/lib/libcups.so.2) by 0x4359D52: cupsGetDests2 (in /usr/lib/libcups.so.2) by 0x435A1B4: cupsGetDests (in /usr/lib/libcups.so.2) 1,440,020 bytes in 1 blocks are possibly lost in loss record 181 of 182 at 0x4026864: malloc (vg_replace_malloc.c:236) by 0x415D0EB: cv::fastMalloc(unsigned int) (in /usr/local/lib/libopencv_core.so.2.3.1) by 0x4A5DE36: (below main) (libc-start.c:226) ---DrawImage is the only thing below main 67,108,864 bytes in 4 blocks are possibly lost in loss record 182 of 182 at 0x4026864: malloc (vg_replace_malloc.c:236) by 0x473C057: _capture_V4L2(CvCaptureCAM_V4L*, char*) (in /usr/local/lib/libopencv_highgui.so.2.3.1) A: Well, at a minimum you never call SDL_FreeSurface() on atr.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600526", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Regex: Optional HTML tags in HTML? I need to parse some values from HTML. I'm using the following regex to parse out some groups, but am having difficulty when there are optional tags in the middle of the HTML. I need some rule to pull out the values from repeated version of the HTML page, even when the optional tags are included. onclick="return raise('SelectFare', new SelectFareEventArgs(1, 3, 'F'))" required="true" requiredError="Please select a flight and fare in every market."></td><td>Regular Fare</td><td>Adult<br></td><td align="right" style="font-size:110%;">91.99 EUR<br><div style="font-style: italic; font-size: 10px;">Only<span style="color: red;"> 4 </span>seats left at this fare</div></td><td></td><td><b>Fri</b>30 Sep 11<br><b>Flight</b>FR 818</td><td>15:10 Depart<br>16:15 Arrive</td></tr><tr id="1_2011_8_30_23_45_00"><td><div class="planeImg1" title="Click to select this fare on this flight"></div></td><td><input For example, the optional <div style="font-style: italic; font-size: 10px;">Only<span style="color: red;"> 4 </span>seats left at this fare</div> section of this is messing it up. tr><tr id="1_2011_9_21_16_05_00"><td><div class="planeImg1" title="Click to select this fare on this flight"></div></td><td><input id="AvailabilityInputFRSelectView_RadioButtonMkt1Fare2" type="radio" name="AvailabilityInputFRSelectView$market1" value="H~HDIS1~XXXC~~RoundFrom|FR~ 816~ ~~DUB~10/21/2011 14:55~EDI~10/21/2011 16:05" onclick="return raise('SelectFare', new SelectFareEventArgs(1, 2, 'H'))" required="true" requiredError="Please select a flight and fare in every market."></td><td>No Taxes</td><td>Adult<br></td><td align="right" style="font-size:110%;"><strike style="color:#F00;font-size:80%;"><b style="color: #999;">22.99 EUR</b></strike>  (-35%) <br>14.94 EUR<br></td><td></td><td><b>Fri</b>21 Oct 11<br><b>Flight</b>FR 816</td><td>14:55 Depart<br>16:05 Arrive</td></tr><tr id="1_2011_9_21_16_15_00"><td><div class="planeImg1" title="Click The <strike . . </strike>. . (-35%). . <br>14.94 EUR<br></td> part of the HTML above is messing it up as well. This is the regex I'm trying (and various other versions!!): "Please select(?:.*?)<td>(.*?)</td><td>(.*?)<br></td><td align=\"right\" style=\"font-size:110%;\">(.*?)<br>(.*?)<br>(?:.*?)</b>(.*?)<br><b>Flight</b>(.*?)</td><td>(.*?)<br>(.*?)</td>" I'd appreciate any help at all on this, or even a reference to learning how to parse out optional HTML tags altogether. Thanks. A: You can't parse (X)HTML with RegEx, so don't do it. You need to use a proper parser that will build you a Document Object Model (DOM). As you have tagged your question with JavaScript, I recommend that you use jQuery to build an object graph of your HTML, simply like this: var $document = $(html); This $document object can now be operated on with methods like $document.find() to dig out the elements you want from the HTML.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600533", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Add video to an iPad application Possible Duplicate: Using MPMoviePlayerViewController in SDK 3.2 for iPad I am writing an application for iPad. till now I have a splash screen then a home screen. Home screen has 6 buttons. Pressing a button on the second or home screen takes you to the third screen which has two options a)Play Video b)read document. Now if play video is pressed it plays the video corresponding to the button pressed on second or home screen. similarly for the Read document, it opens a pdf file respective to the button pressed on home screen. Now I want to add video and pdf to those screens. how can i do it? Any help will be highly appreciated. Best Regards Prateek A: Just load the files into UIWebView, it can handle both videos and PDFs. A: To play the video use the movieplayer framework form apple. Have a look into the sample code from apple here http://developer.apple.com/library/ios/#samplecode/MoviePlayer_iPhone/index.html To read the PDF document and having some gestures for page turn use the following sample code form github: https://github.com/brow/leaves
{ "language": "en", "url": "https://stackoverflow.com/questions/7600534", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Strange character rendered correctly in notepad, but as a control character elsewhere I have a .csv list of businesses. The file has some strange characters in. For example, in this field: Stocktonon-Tees, the first hyphen, between Stockton and on seems to be a character with the value 6 rather than a hyphen, with the value 45. Stack overflow will probably sanatize this so you can't see it, so here is a pastebin: http://pastebin.com/NuyyaQy9 Can anyone explain why this could be? Is it some encoding issue that I have missed? Or a corruption in the dataset? A: Yes, it's almost certainly an encoding issue. A file just consists of binary data - it's how you interpret that binary data that matters. It sounds like Notepad is guessing at the originally-intended encoding, but whatever else you're using isn't. Unfortunately you haven't said anything about what software is trying to read the file or what wrote it in the first place - but you should look at what encoding Notepad thinks it is, and work from there. If it's your code that wrote the file out, and you get to decide the encoding, I'd recommend UTF-8 as a good general purpose, platform-portable encoding.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600536", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Supply specific implementation to an interface dependency only for a specific component I implemented Decorator pattern on BooCustom public class BooDefault : IBoo{} public class BooCustom : IBoo { public BooCustom(IBoo boo) { } } than I have a component Foo public class Foo : IFoo { public Foo(IBoo boo) { } } that depends on IBoo and only for this one I need BooCustom be the implementation for IBoo. Any components depending on IBoo but Foo will use BooDefault including BooCustom. Only Foo needs to have his IBoo dependency resolved by BooCustom instead of BooDefault. How can I accomplish this resolution with windsor? Component.For<IFoo>().ImplementedBy<Foo>() .Supply_BooCustom_as_Concrete_for_IBoo - Foo Dependency A: Look into Handler Selectors. You should be able to create one that checks if the type requesting an IBoo is Foo. If so, it can return a specific component (in this case, the BooCustom).
{ "language": "en", "url": "https://stackoverflow.com/questions/7600540", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: rails association I have following tables: create table files ( id int auto_increment primary_key name varchar(255) ) create table users ( id int auto_increment primary_key name varchar(255) ) create table admins ( file_id int user_id int ) I would like to be able to say get the user names of the file admin. How do I create an association to get this one If I do has_many :admins on the files, then I can do file.admins to get the ids and to get the user names of those admins I would have to sub queries using the Find. I would like to avoid that one A: For Rails questions, rather than sharing your database create-table syntax, you should share your database migrations (just open up schema.rb and copy/paste). It looks like you just have users, some of whom have admin privileges. The easier way of doing this is to just have a t.boolean :admin, :default => false column on your user model. A nice benefit of this approach is that Active Record will provide you with a User#admin? method that is highly readable in conditionals and such (i.e. <%= render 'admin_menu' if @user.admin? %>). This also sidesteps your concerns about additional queries to get the usernames after getting the listed admins. # app/models/file.rb class File < ActiveRecord::Base belongs_to :user end @files = File.where(:something => true).include(:user) @files.map(&:name) #=> ['Bob', 'Cindy', ...]
{ "language": "en", "url": "https://stackoverflow.com/questions/7600548", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: call a function for :condition in association I want to display sent messages by the user. Problem is drafts and sent message contents are stored in the same table, so I want to put a condition on the following association from user.rb has_many :sent_messages, :class_name => "Message", :foreign_key => "user_id", :conditions => [#it has been sent!] I thought of using a is_sent method from message.rb def is_sent current_user.drafts.find_by_message_id(:first, self.id).empty? end How can i call this method in the :condition of my association? Would it be preferable to use a column in my Message table specifying if the stored message has been sent or not? Thanks! A: I would add a boolean sent column to Message, and use this condition in the has_many: :conditions => { :sent => true } This would also give you the function sent? in Message, eliminating your is_sent function. Note that using a question mark like that in function names in Ruby is common practice, and is_ is frowned upon.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600555", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Explorer doesn't release IDataObject when doing a drag/drop I'm implementing drag-and-drop in my application. I'm having a problem with Windows Explorer not releasing my IDataObject after a drag-and-drop operation. To isolate the problem, I've implemented a very simple drag-and-drop source that should compile in most any Win32 compiler. The data object contains no data; as you can see everything is very simple. The data object contains tracing that can be viewed with DebugView to indicate when it is created and when it is destroyed. To reproduce: * *Start the drag by holding down the mouse button. *Drag-and-drop the object into an open Windows Explorer window. *Observe the output in DebugView; sample output: [4964] gdo ctor [4964] gds ctor [4964] gds dtor This output indicates that the data source was destructed, but somebody is still holding a reference to my IDataObject! *Start dragging a file in the same Explorer window. Even though I'm not at all interacting with my project at this time, it causes gdo dtor to be printed - indicating that the final reference to the IDataObject was released. I'm running Windows 7 64-bit. It's interesting to note that some Explorer windows do release the data object right away after the drop; others don't seem to do that until you start dragging a different object into the Explorer window as indicated in step #4. It also seems to depend on where in the window I drop the object - some places cause the object to be immediately released and others don't. It's very strange! My questions are these: * *Is this normal for Explorer to do this? Why is this? Or do I have a bug in my code? It's very disconcerting to see COM objects still referenced when my application terminates! Also it means that the resources held by IDataObject are tied up until Explorer decides to release the object. *If this is indeed normal behavior (and even if it isn't, I guess I should cope with ill-behaved drop targets), then what is the best practice for cleaning up this unreleased COM object when the application terminates? I'm writing in C++ Builder and using ATL, and when the user tries to close the application, they get a very unfriendly "There are still active COM objects in this application, blah blah blah. Are you sure you want to close this application?" - presumably generated by ATL which is noticing there are unreleased COM objects - generally a bad thing on application shutdown. Here's some sample code. It implements an IDataObject that provides no data, and a very basic IDropSource. Of course, the real application provides data via IDataObject but I found this basic implementation is enough to reproduce the issue. I wrote it in C++ Builder but 90% of it is portable Win32 code. Just add a label or other object to the GUI toolkit of choice (MFC, WinForms with C++/CLI, Qt, wxWidgets, straight Win32, whatever) and tie the appropriate code to the MouseDown event. I can't think of any bugs in this code that would cause this behavior, but that doesn't mean I didn't miss any! class GenericDataObject : public IDataObject { public: // basic IUnknown implementation ULONG __stdcall AddRef() { return InterlockedIncrement(&refcount); } ULONG __stdcall Release() { ULONG nRefCount = InterlockedDecrement(&refcount); if (nRefCount == 0) delete this; return nRefCount; } STDMETHODIMP QueryInterface(REFIID riid, void **ppvObject) { if (!ppvObject) return E_POINTER; if (riid == IID_IUnknown) { *ppvObject = static_cast<IUnknown*>(this); AddRef(); return S_OK; } else if (riid == IID_IDataObject) { *ppvObject = static_cast<IDataObject*>(this); AddRef(); return S_OK; } else { *ppvObject = NULL; return E_NOINTERFACE; } } // IDataObject members STDMETHODIMP GetData (FORMATETC *pformatetcIn, STGMEDIUM *pmedium) { return DV_E_FORMATETC; } STDMETHODIMP GetDataHere (FORMATETC *pformatetc, STGMEDIUM *pmedium) { return E_NOTIMPL; } STDMETHODIMP QueryGetData (FORMATETC *pformatetc) { return DV_E_FORMATETC; } STDMETHODIMP GetCanonicalFormatEtc (FORMATETC *pformatectIn, FORMATETC *pformatetcOut) { return DV_E_FORMATETC; } STDMETHODIMP SetData (FORMATETC *pformatetc, STGMEDIUM *pmedium, BOOL fRelease) { return E_NOTIMPL; } STDMETHODIMP EnumFormatEtc (DWORD dwDirection, IEnumFORMATETC **ppenumFormatEtc) { return E_NOTIMPL; } STDMETHODIMP DAdvise (FORMATETC *pformatetc, DWORD advf, IAdviseSink *pAdvSink, DWORD *pdwConnection) { return OLE_E_ADVISENOTSUPPORTED; } STDMETHODIMP DUnadvise (DWORD dwConnection) { return OLE_E_ADVISENOTSUPPORTED; } STDMETHODIMP EnumDAdvise (IEnumSTATDATA **ppenumAdvise) { return OLE_E_ADVISENOTSUPPORTED; } public: GenericDataObject() : refcount(1) {OutputDebugString("gdo ctor");} ~GenericDataObject() {OutputDebugString("gdo dtor");} private: LONG refcount; }; class GenericDropSource : public IDropSource { public: // basic IUnknown implementation ULONG __stdcall AddRef() { return InterlockedIncrement(&refcount); } ULONG __stdcall Release() { ULONG nRefCount = InterlockedDecrement(&refcount); if (nRefCount == 0) delete this; return nRefCount; } STDMETHODIMP QueryInterface(REFIID riid, void **ppvObject) { if (!ppvObject) return E_POINTER; if (riid == IID_IUnknown) { *ppvObject = static_cast<IUnknown*>(this); AddRef(); return S_OK; } else if (riid == IID_IDropSource) { *ppvObject = static_cast<IDropSource*>(this); AddRef(); return S_OK; } else { *ppvObject = NULL; return E_NOINTERFACE; } } // IDropSource members STDMETHODIMP QueryContinueDrag (BOOL fEscapePressed, DWORD grfKeyState) { if (fEscapePressed) { return DRAGDROP_S_CANCEL; } if (!(grfKeyState & (MK_LBUTTON | MK_RBUTTON))) { return DRAGDROP_S_DROP; } return S_OK; } STDMETHODIMP GiveFeedback (DWORD dwEffect) { return DRAGDROP_S_USEDEFAULTCURSORS; } public: GenericDropSource() : refcount(1) {OutputDebugString("gds ctor");} ~GenericDropSource() {OutputDebugString("gds dtor");} private: LONG refcount; }; // This is the C++ Builder-specific part; all I did was add a label to the default form // and tie this event to it. void __fastcall TForm1::Label1MouseDown(TObject *Sender, TMouseButton Button, TShiftState Shift, int X, int Y) { OleInitialize(NULL); GenericDataObject *o = new GenericDataObject; GenericDropSource *s = new GenericDropSource; DWORD effect = 0; DoDragDrop(o, s, DROPEFFECT_COPY, &effect); o->Release(); s->Release(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7600556", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: AES cryption quellcode I need a small, like a two pieced, version of an AES encryption. I googled and found AES - Advanced Encryption Standard (source code), but the code seems to be written for Windows and I need a multi-platform one. Is there any other small version of an AES encrpytion known or a fix for the used functions which seem to be unknown on Linux? My compiler says that those are unknown functions: ./aes/AES.cpp:198:17: error: ‘_rotl’ was not declared in this scope ./aes/AES.cpp:608:20: error: ‘_rotr’ was not declared in this scope I also got: ./aes/AES.cpp:764:34: error: ‘memset’ was not declared in this scope ./aes/AES.cpp:770:36: error: ‘memcpy’ was not declared in this scope As those should be known, considering those includes: #include "AES.hpp" #include <assert.h> #include <stdio.h> #include <cstdio> #include <cstdlib> #include <fstream> #include <iostream> A: Use a well-tested crypto library, like cryptlib or OpenSSL, instead of some random snippets found on 40th page of search results. Depending on what you're doing, you probably also should be using higher-level constructs rather than AES directly. A: The reference implementation for AES can be found here: http://www.efgh.com/software/rijndael.htm. The main source file only includes <stdio.h>, but it doesn't even depend on that; you should have absolutely no problem using it on any platform. A: since this comes up high in a google search for that error, here's what I did for my program which was refusing to compile on an x64 CentOS system that lacks ia32intrin.h: #if !defined(_rotr) && (defined(__i386__) || defined(__x86_64__)) static inline unsigned int _rotr(unsigned int n, const int count) { asm volatile ( "rorl %1, %0;" : "=r" (n) : "nI" (count), "0" (n) ); return n; } #endif as avakar mentioned, you need to include cstring, or alternatively string.h, to get memset and memcpy. the code for _rotl would be identical except for the opcode mnemonic, which would be roll.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600557", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL Server 2008 Sessions We are extremely new to ASP.net...actually working with an outside consultant which I don't currently have access to. I am looking for: * *Good documentation/best practices for session and session management. I'm finding some info now: http://support.microsoft.com/kb/317604 *Review of application below for comments about how to best handle this scenario. We have the following scenario: * *OEM machine on floor providing status UPDATES every x.x seconds to Device_Status table. *When ASP.net client/user wants to view status of a particular machine, I want to notify the OEM machine on the floor to increase update rate to near real-time. Potentially with "realtimeupdate" flag in Device_Status table. *When ASP.net client/user moves on or logs out, update rate needs to return to x.x seconds. Since we are very new to ASP.net, we don't have any clue about sessions and session management or if it is possible. The only problem I see so far is if the ASP.net client connection is terminated prior to setting the "realtimeupdate" flag to 0. If this happens, the OEM machine will continue to provide real-time updates when they are no longer needed. A: you can't count on a browser (or the user) to say "hey I'm done". People walk away from thr PC, surf to stackoverflow.com, hit the X to close the browser, etc. you'll need to code your web page to request "live" frequency with every page refresh. and have some independent server process turn off the "live" frequency if you don't get a page refresh asking for "live" frequency after some set amount of time. In addition to your page turning it off if the user asks for that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600558", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do you handle form validation, especially with nested models, in Node.js + Express + Mongoose + Jade How are you handling form validation with Express and Mongoose? Are you using custom methods, some plugin, or the default errors array? While I could possibly see using the default errors array for some very simple validation, that approach seems to blow up in the scenario of having nested models. A: I personaly use express-form middleware to do validation; it also has filter capabilities. It's based on node-validator but has additional bonuses for express. It adds a property to the request object indicating if it's valid and returns an array of errors. I would use this if you're using express. A: I personally use node-validator for checking if all the input fields from the user is correct before even presenting it to Mongoose. Node-validator is also nice for creating a list of all errors that then can be presented to the user. A: Mongoose has validation middleware. You can define validation functions for schema items individually. Nested items can be validated too. Furthermore you can define asyn validations. For more information check out the mongoose page. var mongoose = require('mongoose'), schema = mongoose.Schema, accountSchema = new schema({ accountID: { type: Number, validate: [ function(v){ return (v !== null); }, 'accountID must be entered!' ]} }), personSchema = new schema({ name: { type: String, validate: [ function(v){ return v.length < 20; }, 'name must be max 20 characters!'] }, age: Number, account: [accountSchema] }), connection = mongoose.createConnection('mongodb://127.0.0.1/test'); personModel = connection.model('person', personSchema), accountModel = connection.model('account', accountSchema); ... var person = new personModel({ name: req.body.person.name, age: req.body.person.age, account: new accountModel({ accountID: req.body.person.account }) }); person.save(function(err){ if(err) { console.log(err); req.flash('error', err); res.render('view'); } ... });
{ "language": "en", "url": "https://stackoverflow.com/questions/7600559", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: RESTful ASP.NET webservice - How can I return JSON-serialized Dictionary? I have a RESTful web service that returns JSON-serialized data. It can successfully serialize a Dictionary<string, string> object, but I would like each function to be able to return Dictionary<string, object>. When I return Dictionary<string, string>, I get the expected JSON response. But when I try to return Dictionary<string, object>, I get this response: ReadResponse() failed: The server did not return a response for this request. So, ON TO THE CODE! Here is the Dictionary<string, object> code that fails: [OperationContract] [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] public Dictionary<string, object> Test(String Token, String Id) { Dictionary<string, object> testresults = new Dictionary<string, object>(); testresults.Add("Test1Key", "Test1Value"); Dictionary<string, string> innertestresults = new Dictionary<string, string>(); innertestresults.Add("InnerTest1Key", "InnerTest1Value"); innertestresults.Add("InnerTest2Key", "InnerTest2Value"); testresults.Add("Test2Key", innertestresults); return testresults; } And, just for kicks/reference, here is the Dictionary<string,string> code that works perfectly: [OperationContract] [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] public Dictionary<string, string> Test(String Token, String Id) { Dictionary<string, string> testresults = new Dictionary<string, string>(); testresults.Add("Test1Key", "Test1Value"); testresults.Add("Test2Key", "Test2Value"); testresults.Add("Test3Key", "Test3Value"); return testresults; } If anybody has any ideas of how to get this to work (or any alternative ways of doing this to get the same end result), please do let me know! I'm pretty open on how to do this. On the topic of usage... the reason I need the mix is so that I can return results like this (where the "Data" part could be ANYTHING... not necessarily something with the keys ID, Type, and MaxUsers): {"Status":"Success","Data":{"ID":"1234","Type":"Live","MaxUsers":"5"}} {"Status":"Failure","Error":"ID does not exist"} Thank you all very much! A: I can recreate the error you are experiencing but have had no luck getting the service to serialize the Dictionary<string, object> object automatically. One workaround is to serialize the object in code using the JavaScriptSerializer class and return the resulting string like so: using System.Web.Script.Serialization; ... [OperationContract] [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] public string Test(String Token, String Id) { Dictionary<string, object> testresults = new Dictionary<string, object>(); testresults.Add("Test1Key", "Test1Value"); Dictionary<string, string> innertestresults = new Dictionary<string, string>(); innertestresults.Add("InnerTest1Key", "InnerTest1Value"); innertestresults.Add("InnerTest2Key", "InnerTest2Value"); testresults.Add("Test2Key", innertestresults); JavaScriptSerializer serializer = new JavaScriptSerializer(); string json = serializer.Serialize(testresults); return json; } Hope this helps. Edit (based on comments) Ok, spent a little time researching this and it seems as though you need to explicity declare the types that will be present in the object graph when serialization occurs using the ServiceKnownType attribute. The ServiceKnownType needs to be added as an attribute of your service and in your case you need to declare the Dictionary<string, string> type like so: [ServiceKnownType(typeof(Dictionary<string, string>))] [ServiceContract(Namespace = "WebApplication1")] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class Service... A: I was banging my head on similar issue, When service was getting executed without any exception but ajax call was not executing success method and in each browser, error message was not consistent. When I was returning Dictionary. My object class was having some properties of type DateTime. I found few posts on google regarding DateTime format in JSON and C#. I changed those properties from DateTime to string and worked. Regards.
{ "language": "en", "url": "https://stackoverflow.com/questions/7600562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is the user email address always returned from requestWithGraphPath:@"me"? Is the user email address always returned from the Facebook Graph API when a user has authorized my app and I call requestWithGraphPath:@"me" ? Or is it possible for a user to hide it in their privacy settings? Thanks! A: It will only be returned if you prompt them for email extended permissions and they accept it (and haven't later re-voked it).
{ "language": "en", "url": "https://stackoverflow.com/questions/7600565", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }