text
stringlengths
8
267k
meta
dict
Q: SITE_ROOT = Variable? I'd very much appreciate if someone could help me with a solution. How can I get this: define ('SITE_ROOT', $_SERVER['DOCUMENT_ROOT'] . SITE_BASE); to look something like this: define ('SITE_ROOT', [variable from root.com/directory/data.php] ); Many thanks. A: <?php include_once("/directory/data.php"); define('SITE_ROOT', $variable); ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7563220", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: problem uploading file from Android using multipart I have the following code to send a file (mpeg file - about 20kb) from the phone to the server. However, it fails at the server end. Can anyone kindly telly me what mistake I am making at the client end ? Thanks. ByteArrayOutputStream bos = new ByteArrayOutputStream(); //bm.compress(CompressFormat.JPEG, 75, bos); byte[] data = bos.toByteArray(); HttpClient httpClient = new DefaultHttpClient(); HttpPost postRequest = new HttpPost("http://example.com/upload.php"); File file= new File("/mnt/sdcard/enca/aha.mpeg"); FileBody bin = new FileBody(file); MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); reqEntity.addPart("uploaded", bin); reqEntity.addPart("random", new StringBody(encameo1.random)); reqEntity.addPart("fingerPrint", new StringBody(encameo1.fingerprint)); postRequest.setEntity(reqEntity); HttpResponse response = httpClient.execute(postRequest); BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); String sResponse; StringBuilder s = new StringBuilder(); while ((sResponse = reader.readLine()) != null) { s = s.append(sResponse); } System.out.println("Response: " + s); php code: <?php $target_path = "uploaded_files/"; $target_path = $target_path . basename( $_FILES['userfile']['name']); if(move_uploaded_file($_FILES['userfile']['tmp_name'], $target_path)) { echo "The file ". basename( $_FILES['userfile']['name'])." has been uploaded"; } else { echo "There was an error uploading the file, please try again!"; } ?> A: You're sending the part with the name uploaded: reqEntity.addPart("uploaded", bin); However, PHP is expecting a part with the name userfile: if(move_uploaded_file($_FILES['userfile']['tmp_name'], $target_path)) Align it to be the same.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563227", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Explanation of a BLOB and a CLOB I am looking for a real good explanation of a BLOB and CLOB data. I am looking for the great of that explains in plain English. A: It's pretty straight forward. The difference is that your storing large data objects within the table as a column that are either character based (i.e. A CLOB) or binary based (i.e. a BLOB) Think of it in the same terms of how you would open a file as text vs when you open it as binary data. VARCHARS etc. would still be preferred for string data types that are relatively short and in my mind a singular piece of data. For example a name, a street name, dept name etc. When you're looking to store something along the lines of a XML configuration file or the like, you would want to consider storing it as a CLOB. If you're storing say images, then a BLOB would be the logical choice. There are discussions about whether it's better to store the actual image or config file within the table vs storing a path to the actual file instead but I'll leave that for another question. A: A BLOB is a Binary Large Object which can hold anything you want including images and media files. Anything stored as a binary file. A CLOB is a Charactor Large Object, which will hold charactors (text), Basically this makes it a huge string field. CLOB also supports charactor encoding meaning it is not just ascii charactors. The two links to Oracle's FAQ will provide specific information for the usage of each. A: BLOB's (Binary Large OBject) store binary files: pictures, text, audio files, word documents, etc. Anything you can't read with the human eye. You can't select them via SQL*Plus. CLOB's (Character Large OBjects) store character data. They are often used to store XML docs, JSON's or just large blocks of formatted or unformatted text. A: The Oracle Concepts Guide is the best source for an explanation of LOB datatypes. make sure you read the concepts guide at least once a year and the concept guide specific to the version of oracle you have. Every time I read it I learn something new. Select * from v$version
{ "language": "en", "url": "https://stackoverflow.com/questions/7563235", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Javascript image gallery preventing the default Hi i have a question regarding the image gallery i am trying to create. I have created a thumbnail viewer so when clicked the javascript then displays the thumbnail as a larger image on the same page, but i am required to add a way to still see the larger images when javascript is turned off. Here is my code (javascript) function changeImage(el) { evt.preventDefault(evt); var elem = document.getElementById("slide"); elem.src = "Assets/images/big/"+el+".jpg"; } (HTML) <div id="gallery"> <img id="slide" src="Assets/images/big/0.jpg" onClick="next();"> </div> <div id="thumb"> <ul class="thumbnail"> <li><a href="Assets/images/big/0.jpg" onClick="changeImage('0');"><img id="thumb" src="Assets/images/thumbs/0.jpg" /></a></li> <li><a href="Assets/images/big/1.jpg" onClick="changeImage('1');"><img id="thumb" src="Assets/images/thumbs/1.jpg" /></a></li> <li><a href="Assets/images/big/2.jpg" onClick="changeImage('2');"><img id="thumb" src="Assets/images/thumbs/2.jpg" /></a></li> <li><a href="Assets/images/big/3.jpg" onClick="changeImage('3');"><img id="thumb" src="Assets/images/thumbs/3.jpg" /></a></li> <li><a href="Assets/images/big/4.jpg" onClick="changeImage('4');"><img id="thumb" src="Assets/images/thumbs/4.jpg" /></a></li> <li><a href="Assets/images/big/5.jpg" onClick="changeImage('5');"><img id="thumb" src="Assets/images/thumbs/5.jpg" /></a></li> <li><a href="Assets/images/big/6.jpg" onClick="changeImage('6');"><img id="thumb" src="Assets/images/thumbs/6.jpg" /></a></li> <li><a href="Assets/images/big/7.jpg" onClick="changeImage('7');"><img id="thumb" src="Assets/images/thumbs/7.jpg" /></a></li> </ul> </div><!-- thumb--> Now i had it so the thumbnail viewer was working but after adding the javascript fail option it no longer displays the image in the gallery but instead on a separate page as it would if there was no javascript, what would be the easiest way to fix this so when the javascript is working the thumbnail image is shown in the gallery when it is not it goes into a seperate page? Any help is much appreciated A: The evt variable is not declared anywhere. You would need to pass the event object into the function. Alternatively, you could put return false at the end of your onclick attributes. A: Remove evt.preventDefault(evt); and change <a href="Assets/images/big/i.jpg" onClick="changeImage('i');"><img id="thumb" src="Assets/images/thumbs/i.jpg" /></a> (i from 0 to 7) in your HTML codes to <img class="thumb" src="Assets/images/thumbs/i.jpg" onclick="changeImage('i');" style="cursor:pointer;"/> (<a> is removed, and style attribute is added to change the mouse cursor to pointer, and changed id to class - multiple elements having same ID is bad.) A: Return false from the event handler: function changeImage(el) { var elem = document.getElementById("slide"); elem.src = "Assets/images/big/" + el + ".jpg"; return false; } And in html add return statement too: <ul class="thumbnail"> <li><a href="Assets/images/big/0.jpg" onClick="return changeImage('0');"><img id="thumb" src="Assets/images/thumbs/0.jpg" /></a></li> <li><a href="Assets/images/big/1.jpg" onClick="return changeImage('1');"><img id="thumb" src="Assets/images/thumbs/1.jpg" /></a></li> <li><a href="Assets/images/big/2.jpg" onClick="return changeImage('2');"><img id="thumb" src="Assets/images/thumbs/2.jpg" /></a></li> <li><a href="Assets/images/big/3.jpg" onClick="return changeImage('3');"><img id="thumb" src="Assets/images/thumbs/3.jpg" /></a></li> <li><a href="Assets/images/big/4.jpg" onClick="return changeImage('4');"><img id="thumb" src="Assets/images/thumbs/4.jpg" /></a></li> <li><a href="Assets/images/big/5.jpg" onClick="return changeImage('5');"><img id="thumb" src="Assets/images/thumbs/5.jpg" /></a></li> <li><a href="Assets/images/big/6.jpg" onClick="return changeImage('6');"><img id="thumb" src="Assets/images/thumbs/6.jpg" /></a></li> <li><a href="Assets/images/big/7.jpg" onClick="return changeImage('7');"><img id="thumb" src="Assets/images/thumbs/7.jpg" /></a></li> </ul>
{ "language": "en", "url": "https://stackoverflow.com/questions/7563241", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Download Pictures from web using webBrowser control First excuse for my English i'm from spain. I am a little worried because i cannot been able to finish my project in the school, I am trying to develop an application in visual basic 6 to discharge the cd covers (Album Art) from internet using the webbrowser control, i put this path to navigate: "http://www.google.com.co/search? hl=es&safe=active&gbv=2&biw=1280&bih=821&tbm=isch&sa=1&q=%22heroes+del+silencio%22%2B%22avalancha%22%2Balbum+art+small&oq=%22heroes+del+silencio%22%2B%22avalancha%22%2Balbum+art+small&aq=f&aqi=&aql=1&gs_sm=e&gs_upl=" This display the covers that I am needing, but i'm trying to get the first Picture filename or URL and save this direct to a Folder In my Pc, please can some help to me, Thanks... I will be very grateful for your help A: I have written a part of code and you can continue to finish your program. This is a code of sub, which gives you HTML Code of web-pages: Function GetHTMLCode(strURL As String) As String Dim objHttp As Object, strText As String Set objHttp = CreateObject("MSXML2.ServerXMLHTTP") objHttp.Open "GET", strURL, False objHttp.setRequestHeader "User-Agent", _ "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)" objHttp.Send ("") strText = objHttp.responseText Set objHttp = Nothing GetHTMLCode = strText End Function I have found that all the links of pictures in Google Pictures are starting with this HTML code : src="http:// and end with this : " The links of pictures are between these 2 lines!!! You can use GetHTMLCode to get all HTML code of current web page. Then continually find these 2 lines using "instr" function , and download the links between them. Problem Solved! Please vote , if my answer is useful :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7563261", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: EF Code-First - Storing IEnumerable Of Enum I'm using EF June CTP which has simple enum support. I have a MVC 3 view which has checkboxes that when submitted are retrieved as an array of some enum. public enum CheckBox : byte { VALUE_1 = 1, VALUE_2 = 2, ... } I need to take that colelction of enums ((IEnumerable)) and store that via code-first approach. Right now, that property is being ignored altogether. I'm not sure if it would ultimately, when works, would create a separate one-to-many table or store all the values in one column but any ideas would be great. Just need to store it. Once it stores it, it would be ultimately be awesome if it didn't create a separate one-to-many table and somehow store it within the same table as some delimited string but I'm reaching here probably. Thank you. UPDATE 1 Tried adding [Flags] to the enum to no avail. It gets completely ignored during table generation. My Model property is: public IEnumerable<CheckBox> Values { get; set; } A: You should use a [Flags] enum instead of a collection: [Flags] public enum Checboxes { SomeValue = 1, OtherValue = 2, ThirdValue = 4 } public Checkboxes Boxes { get; set; } Boxes = Checkboxes.SomeValue | Checkboxes.OtherValue;
{ "language": "en", "url": "https://stackoverflow.com/questions/7563262", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Doubly nested EL variables? I'm using Spring MVC for my controller, and JSPs are my presentation layer. Inside my Spring controller, I have: model.put("issues", dataManager.getIssues()); model.put("functions", dataManager.getFunctions()); So now inside my JSP, I have access to ${requestScope['issues']} ${requestScope['functions']} That's all well and good. But in order for my code to be extensible, I would like to store the variable name issues and functions inside the database, which will then be accessible through a property on a configs object that's being looped over. So what I'd like to end up with is something like the following: <c:forEach items="${configs}" var="cfg"> <c:if test="${cfg.configType == 'select'}"> <th>${cfg.header}</th> <td><myTagLib:select values="${requestScope['${cfg.selectorName}']}" /></td> </c:if> </c:forEach> Where ${cfg.selectorName} will hold either issues or functions in this example. A: You're close. You only need to remove the nested ${} since that's invalid syntax. <myTagLib:select values="${requestScope[cfg.selectorName]}" />
{ "language": "en", "url": "https://stackoverflow.com/questions/7563267", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Vows with Async nested topics - scope problem I want my vow to have access to outerDocs and innerDocs from my topics but it doesn't. 'ASYNC TOPIC': { topic: function() { aModel.find({}, this.callback); }, 'NESTED ASYNC TOPIC': { topic: function(outerDocs) { anotherModel.find({}, this.callback(null, innerDocs, outerDocs)); }, 'SHOULD HAVE ACCESS TO BOTH SETS OF DOCS': function(err, innerDocs, outerDocs) { console.log(err, innerDocs, outerDocs); return assert.equal(1, 1); } } What am I doing wrong? A: You can't set arguments to the callback like that, the find function will do that itself. Do this instead: topic: function(outerDocs) { var self = this; anotherModel.find({}, function(err, docs) { self.callback(err, docs, outerDocs); }); },
{ "language": "en", "url": "https://stackoverflow.com/questions/7563268", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Find only non-inherited interfaces? I am trying to perform a query on the interfaces of a class via reflection, however the method Type.GetInterfaces() returns all the inherited interfaces also. etc public class Test : ITest { } public interface ITest : ITesting { } The code typeof(Test).GetInterfaces(); Will return a Type[] containing both ITest and ITesting, where as I only want ITest, is there another method which allows you to specify inheritance? Thanks, Alex. EDIT: From the answers below I gathered this, Type t; t.GetInterfaces().Where(i => !t.GetInterfaces().Any(i2 => i2.GetInterfaces().Contains(i))); The above seems to work, correct me in the comments if it does not A: A bigger expert in .NET can correct me if I am wrong, but I don't believe this is possible. Internally I believe the .NET framework doesn't actually maintain that hierarchy, and it gets flattened when it is compiled to IL code. For example, the C# code: class Program : I2 { static void Main(string[] args) { } } interface I1 { } interface I2 : I1 { } After it is built into IL code, it is: .class private auto ansi beforefieldinit ReflectionTest.Program extends [mscorlib]System.Object implements ReflectionTest.I2, ReflectionTest.I1 { ... Which is exactly the same as class Program : I1, I2 However, also in the IL is: .class interface private abstract auto ansi ReflectionTest.I2 implements ReflectionTest.I1 { ... This means that you could write some logic to get (from my example) I1 and I2 from the Program class, then query each of those interfaces to see if they implement one of the others... In other words, since typeof(I2).GetInterfaces() contains I1, then you can infer that since typeof(Program).GetInterfaces() returns I1 and I2, then Program might not directly inherit I1 in code. I emphasize might not because this is also valid C# code and would make the same IL code (and also the same reflection results): class Program : I1, I2 { static void Main(string[] args) { } } interface I1 { } interface I2 : I1 { } Now Program both directly and indirectly inherits I1... A: It's not possible to simply retrieve the immediate interfaces, but we have the necessary Type metadata to figure it out. If we have a flattened list of interfaces from the entire inheritance chain, and each interface can tell us which of its siblings it also implements/requires (which they do), we can recursively remove every interface which is implemented or required on a parent. This approach is a little over-aggressive, in that if you declare IFoo and IBar on the immediate class AND IFoo is required by IBar, it will be removed (but really, what is this more than an exercise in curiosity? The practical usefulness of this is unclear to me...) This code is ugly as hell, but I just threw it together in a fresh/bare MonoDevelop install... public static void Main (string[] args) { var nonInheritedInterfaces = typeof(Test).GetImmediateInterfaces(); foreach(var iface in nonInheritedInterfaces) { Console.WriteLine(iface); } Console.Read(); } class Test : ITest { } interface ITest : ITestParent { } interface ITestParent { } public static class TypeExtensions { public static Type[] GetImmediateInterfaces(this Type type) { var allInterfaces = type.GetInterfaces(); var nonInheritedInterfaces = new HashSet<Type>(allInterfaces); foreach(var iface in allInterfaces) { RemoveInheritedInterfaces(iface, nonInheritedInterfaces); } return nonInheritedInterfaces.ToArray(); } private static void RemoveInheritedInterfaces(Type iface, HashSet<Type> ifaces) { foreach(var inheritedIface in iface.GetInterfaces()) { ifaces.Remove(inheritedIface); RemoveInheritedInterfaces(inheritedIface, ifaces); } } } private static void RemoveInheritedInterfaces(Type iface, Dictionary<Type, Type> interfaces) { foreach(var inheritedInterface in iface.GetInterfaces()) { interfaces.Remove(inheritedInterface); RemoveInheritedInterfaces(inheritedInterface, interfaces); } } A: You can try something like this: Type[] allInterfaces = typeof(Test).GetInterfaces(); var exceptInheritedInterfaces = allInterfaces.Except( allInterfaces.SelectMany(t => t.GetInterfaces()) ); so, if you have something like this: public interface A : B { } public interface B : C { } public interface C { } public interface D { } public class Test : A, D { } The code will return A and D A: In my previous attempt I could not succeed. Type[] types = typeof(Test).GetInterfaces(); var directTypes = types.Except (types.SelectMany(t => t.GetInterfaces())); foreach (var t in directTypes) { } Hope this will helps someone. A: It appears there is no trivial method call to do this as basically the following are exactly the same when compiled: MyClass : IEnumerable<bool> and MyClass : IEnumerable<bool>,IEnumerable You can interrogate each interface and ask for its interfaces. And see if they are in the formers list. Unusually, for classes GetInterfaces is recursive. That is to say it gets all levels of inheritance. For interfaces it is not recursive. For instance: IList returns IList and ICollection, but makes no mention about IEnumerable which is implemented by ICollection. However, you are most likely interested in the methods implemented uniquely by each interface and their binding in which case you can use the method GetInterfaceMap(Type). A: try this: Type t = typeof(Test); int max = 0; Type result = null; foreach (Type type in t.GetInterfaces()) { int len = type.GetInterfaces().Length; if (len > max) { max = len; result = type; } } if (result != null) Console.WriteLine(result.FullName); A: Type t = typeof(Test); int max = 0; List<Type> results = new List<Type>(); foreach (Type type in t.GetInterfaces()) { int len = type.GetInterfaces().Length; if (len > max) { max = len; results.Add(type); } } if (results.Count > 0) foreach (Type type in results) Console.WriteLine(type.FullName);
{ "language": "en", "url": "https://stackoverflow.com/questions/7563269", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: iOS: locationManager:didUpdateToLocation:fromLocation: reports speed when not moving I am using locationManager:didUpdateToLocation:fromLocation: to get location updates. Most everything is working well but when I check the newLocation.speed propery while standing still I almost always get a speed value greater than 0. Even when I start getting location updates for the first time and have NEVER even moved I will get positive values after a few updates. Just doing a simple greater than 0 check then setting a UILablel if it is: if (newLocation.speed > 0) { self.speed.text = [NSString stringWithFormat:@"%.2f",[self speed:newLocation.speed]]; } More code from that method: - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { // Check first if we are getting the accuracy we want if (newLocation.horizontalAccuracy < 0) return; // Make sure the update is new not cached NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow]; if (locationAge > 5.0) return; // Check to see if old and new are the same if ((oldLocation.coordinate.latitude == newLocation.coordinate.latitude) && (oldLocation.coordinate.longitude == newLocation.coordinate.longitude)) return; // Make sure our new location is not super far away from old CLLocationDistance dist = [newLocation distanceFromLocation:oldLocation]; NSLog(@"Distance: %f", dist); if (dist > 40) return; // Make sure we have a new location if (!newLocation) return; // Check to see if we are stopped if (newLocation.speed == 0) { self.inMotion = NO; } else if (newLocation.speed > 0) { self.inMotion = YES; } else { // Probably an invalid negative value self.inMotion = NO; }//end // Speed // Should always be updated even when not recording! if (newLocation.speed > 0 && inMotion) { self.speed.text = [NSString stringWithFormat:@"%.2f",[self speed:newLocation.speed]]; NSLog(@"Speed: %f", newLocation.speed); } // Tons more code below that I removed for this post }//end Is this normal? A: How much greater than zero? And for how long? Do all the locations that you are comparing have the same accuracy? In a GPS receiver the speed is usually determined by the change in location between successive location fixes (it can also be computed by measuring doppler shift). Location fixes will vary slightly due to measurement errors or as they become more accurate. The changes in location can make it appear that the device moved. For example, suppose your first fix has an accuracy of 1000m horizontal and your second fix has an accuracy of 300m horizontal, the first position could have been 1000m off of the real location and the second could be 700m away from that first fix even though the device hasn't moved. This translates to a change in location over time which is "speed".
{ "language": "en", "url": "https://stackoverflow.com/questions/7563271", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: setZoomScale: and zoomToRect: works on device but it doesn't on iOS Simulator I have a UIScrollView wich does provide zooming function with pinch gestures,it's controller is conform to UIViewScrollDelegate, implement it's methods and everything... This works perfectly fine on my iOS device,it scrolls and zoom in/out. When it comes to try it on the simulator, it just wont work(the two gray-circles pop out when i press the option key though). Since it works fine on my device, is not a big deal ... but I need it to works on iOS simulator too, because I would like to make a video out of it. What could be the possible problems? Additional info: * *UIScrollView is the main view of the controller mentioned above *UIScrollView is created in the XIB file *it have a subview *I've tried it on every version/device of the iOS simulator(iPad,iPhone,Retina) *Even zoomToRect works fine on device but not on the simulator
{ "language": "en", "url": "https://stackoverflow.com/questions/7563272", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Excel - if and or function The formula I'm trying to write is CellA CellB CellC Total Price Order status Delivery Status** Null Authorised Null Authorised Null $100 Authorised Authorised if cell A = Null and cell C = Null or blank... then "ERROR" How would I write the formula? A: Assuming CellA is A2 and CellC is C2, use this formula below =IF(AND($A2="null",OR($C2="NULL",$C2="")),"ERROR","NoError") if you have assigned variable name to each cell you can use CellA and CellC instead A: Off the top of my head... =IF(A2 == "NULL", IF(OR(C2 == "NULL", C2 == ""), "ERROR", ""), "")
{ "language": "en", "url": "https://stackoverflow.com/questions/7563274", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Sharepoint Deploy web part error When I try to deploy web part, I got the error " The solution needs to install assemblies in the GAC, Any Idea ? Thanks in advance. A: You need to specify allowGacDeployment parameter in STSADM command (or GacDeployment in PowerShell)
{ "language": "en", "url": "https://stackoverflow.com/questions/7563278", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C++ class whose member is a struct: Cannot understand compiler error I want to create a class one of whose private: members is a struct point(see below). The public members ndim and numparticles are set at run-time by the user, which are used to create corresponding arrays inside the class . However I am getting a compiler error. I don't understand where I messed up. The compiler error being displayed: nbdsearch.h:25: error: ‘point’ does not name a type nbdsearch.h:24: error: invalid use of non-static data member ‘nbdsearch::ndim’ nbdsearch.h:31: error: from this location nbdsearch.h:31: error: array bound is not an integer constant before ‘]’ token The class code: class nbdsearch{ public: int ndim,numparticles; point particlevec[numparticles]; private: struct point{ string key; double cood[ndim]; }; }; A: nbdsearch.h:31: error: array bound is not an integer constant before ‘]’ token double cood[ndim]; Array size needs to be a compile time constant and ndim clearly isn't. ndim is a variable. error: ‘point’ does not name a type point particlevec[numparticles]; On line 25, compiler doesn't know what point is. The structure is defined at a later point. Compilers in C++ work on a top to bottom approach(Not sure whether C++0X relaxes this rule). So, what ever types being used should be known to it before hand. Try this - class nbdsearch{ private: struct point{ string key; std::vector<double>cood; }; public: int ndim,numparticles; std::vector<point> particlevec; }; A: point needs to be declared before its use. Try putting the private: block before the public: block. A: There are a few different problems with your code. * *The declaration of point needs to be visible to compiler before you use it *You're trying to create array from variables that are not compile time constants; C++ does not allow creation of variable length arrays. To fix these problems: * *Move the declaration block for point above where you use it. Note that since the definition of point is private, someone calling nbdsearch::particlevec will not be able to store that value. All they could do is pass it along to another member function (or friend function) of nbdsearch. *Change declaration of particlevec to std::vector<point> particlevec. Make a similar change for point::cood. Once the user specifies values for ndim & numparticles use std::vector::resize to size the arrays appropriately.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563287", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Visual Studio - referencing WCF Library directly and the ignoring of serviceHostingEnvironment? Just want to ask you to confirm that I'm right (but may be totally wrong :). Situation: I have a VS2010 Solution with 3 projects A) WCF Library, B) Web Site that host this library C) test application that use the web service. Last I could configure two different ways: adding reference to the WCF Lib or Web Site. I've discovered that when I'm referencing WCF library directly (some may be remember those endpoints http://localhost:8732/Design_Time_Addresses/...) the configuration of custom servicehostfactory in app.config element <serviceHostingEnvironment><serviceActivations>.. is ignored. Since interpretation of serviceHostingEnvironment is responsibility of the host I make an assumption that VS2010 WCF Library Host have such feature - ignore serviceHostingEnvironment? Am I right? P.S. May be I could ask you to point me the doc where I could find the information about VS2010 WCF library's host.. It seems I should get to know better. A: Description of test service host is here. ServiceHostingEnvironment element controls integration with web server = I don't think that any part of this configuration section is used for self hosted services and test host is self hosting. ServiceActivations element contains file-less activation configuration for web server. That means ability to activate service without physical existence of hosting .svc file. That is something which doesn't make sense in self hosted scenario.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563289", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Finishing an Activity from a Broadcast Receiver I have an Activity that I display as modeless when the phone rings (over the phone app). I would like to finish the Activity when either of the following events occur. The first is if I touch anywhere outside the Activity (this is not a problem), the second is if the ringing stops. I am listening for IDLE_STATE in the broadcast receiver but I am not sure on how to call the finish on the activity when I see it. The receiver is not registered by the activity but by the Manifest.xml A: write the code in your receiving broadcast now this will send another broad cast with the intent named "com.hello.action" Intent local = new Intent(); local.setAction("com.hello.action"); sendBroadcast(local); Now catch this intent in the activity with you want to finish it and then call the super.finish() on the onReceive method of your receiver like this public class fileNamefilter extends Activity { ArrayAdapter<String> adapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); IntentFilter filter = new IntentFilter(); filter.addAction("com.hello.action"); registerReceiver(receiver, filter); } BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { finish(); } }; public void finish() { super.finish(); }; } this will finish the activity A: What if you register another broadcast receiver from the activity. Then, when you want to kill it, send a broadcast message from the broadcast receiver that you mentioned. A: I actually ended up adding a PhoneStateListener in the Activity to listen for IDLE_STATE. A: After a long R&D over internet i have solved my problem. The below code is helpful if you start an activity from broadcast receiver and clear all activity stack instance. @Override public void onBackPressed() { if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { moveTaskToBack(true); } } A: I used this code to solve my problem. finish is the method of Activity, so call Activity and context like: if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) { Log.e(TAG, "Inside EXTRA_STATE_IDLE"); ((Activity) arg0).finish(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7563301", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Dynamic Array in C - realloc I know how to build Dynamically allocated arrays, but not how to grow them. for example I have the following interface.. void insertVertex( vertex p1, vertex out[], int *size); This method takes a vertex and stores it into the out array. After storing the vertex I increase the count of length for future calls. p1 - is the vertex I'm going to add. out[] - is the array I need to store it in (which is always full) length - the current length Vertex is defined as.. typedef struct Vertex{ int x; int y; } Vertex; This is what I'm using in Java.. Vertex tempOut = new Vertex[size +1]; //Code to deep copy each object over tempOut[size] = p1; out = tempOut; This is what I believed I could use in c.. out = realloc(out, (*size + 1) * sizeof(Vertex)); out[(*size)] = p1; However, I keep on receiving an error message that the object was not allocated dynamically. I found a solution that will resolve this.. Instead of using Vertex* I was going to switch to Vertex** and store pointers vs. vertex. However, after switching everything over I found out that I over looked the fact that the unit test will be providing me a Vertex out[] that everything has to be stored in. I have also tried the following with no luck. Vertex* temp = (Vertex *)malloc((*size + 1) * sizeof(Vertex)); for(int i = 0; i < (*size); i++) { temp[i] = out[i]; } out = temp; However, no matter what I do when I test after both of these the array returned has not changed. Update - Requested information out - is defined as an array of Vertex (Vertex out[]) It is originally built with the number of vertex in my polygon. For example. out = (Vertex *)malloc(vertexInPolygon * sizeof(Vertex)) Where vertexInPolygon is an integer of the number of vertex in the polygon. length was a typo that should have been size. Size is an integer pointer int *size = 0; Each time a vertex is in the clipping plane we add it to the array of vertex and increase the size by one. Update To better explain myself I came up with a short program to show what I'm trying to do. #include <stdio.h> #include <stdlib.h> typedef struct Vertex { int x, y; } Vertex; void addPointerToArray(Vertex v1, Vertex out[], int *size); void addPointerToArray(Vertex v1, Vertex out[], int *size) { int newSize = *size; newSize++; out = realloc(out, newSize * sizeof(Vertex)); out[(*size)] = v1; // Update Size *size = newSize; } int main (int argc, const char * argv[]) { // This would normally be provided by the polygon int *size = malloc(sizeof(int)); *size = 3; // Build and add initial vertex Vertex *out = (Vertex *)malloc((*size) * sizeof(Vertex)); Vertex v1; v1.x = 1; v1.y =1; Vertex v2; v2.x = 2; v2.y =2; Vertex v3; v3.x = 3; v3.y =3; out[0] = v1; out[1] = v2; out[2] = v3; // Add vertex // This should add the vertex to the last position of out // Should also increase the size by 1; Vertex vertexToAdd; vertexToAdd.x = 9; vertexToAdd.y = 9; addPointerToArray(vertexToAdd, out, size); for(int i =0; i < (*size); i++) { printf("Vertx: (%i, %i) Location: %i\n", out[i].x, out[i].y, i); } } A: One long-term problem is that you are not returning the updated array pointer from the addPointerToArray() function: void addPointerToArray(Vertex v1, Vertex out[], int *size) { int newSize = *size; newSize++; out = realloc(out, newSize * sizeof(Vertex)); out[(*size)] = v1; // Update Size *size = newSize; } When you reallocate space, it can move to a new location, so the return value from realloc() need not be the same as the input pointer. This might work while there is no other memory allocation going on while you add to the array because realloc() will extend an existing allocation while there is room to do so, but it will fail horribly once you start allocating other data while reading the vertices. There are a couple of ways to fix this: Vertex *addPointerToArray(Vertex v1, Vertex out[], int *size) { int newSize = *size; newSize++; out = realloc(out, newSize * sizeof(Vertex)); out[(*size)] = v1; // Update Size *size = newSize; return out; } and invocation: out = addPointerToArray(vertexToAdd, out, size); Alternatively, you can pass in a pointer to the array: void addPointerToArray(Vertex v1, Vertex **out, int *size) { int newSize = *size; newSize++; *out = realloc(*out, newSize * sizeof(Vertex)); (*out)[(*size)] = v1; // Update Size *size = newSize; } and invocation: out = addPointerToArray(vertexToAdd, &out, size); Neither of these rewrites addresses the subtle memory leak. The trouble is, if you overwrite the value you pass into realloc() with the return value but realloc() fails, you lose the pointer to the (still) allocated array - leaking memory. When you use realloc(), use an idiom like: Vertex *new_space = realloc(out, newSize * sizeof(Vertex)); if (new_space != 0) out = new_space; else ...deal with error...but out has not been destroyed!... Note that using realloc() to add one new item at a time leads to (can lead to) quadratic behaviour. You would be better off allocating a big chunk of memory - for example, doubling the space allocated: int newSize = *size * 2; If you are worried about over-allocation, at the end of the reading loop, you can use realloc() to shrink the allocated space to the exact size of the array. However, there is then a bit more book-keeping to do; you need to values: the number of vertices allocated to the array, and the number of vertices actually in use. Finally, for now at least, note that you should really be ruthlessly consistent and use addPointerToArray() to add the first three entries to the array. I'd probably use something similar to this (untested) code: struct VertexList { size_t num_alloc; size_t num_inuse; Vertex *list; }; void initVertexList(VertexList *array) { // C99: *array = (VertexList){ 0, 0, 0 }; // Verbose C99: *array = (VertexList){ .num_inuse = 0, .num_alloc = 0, .list = 0 }; array->num_inuse = 0; array->num_alloc = 0; array->list = 0; } void addPointerToArray(Vertex v1, VertexList *array) { if (array->num_inuse >= array->num_alloc) { assert(array->num_inuse == array->num_alloc); size_t new_size = (array->num_alloc + 2) * 2; Vertex *new_list = realloc(array->list, new_size * sizeof(Vertex)); if (new_list == 0) ...deal with out of memory condition... array->num_alloc = new_size; array->list = new_list; } array->list[array->num_inuse++] = v1; } This uses the counter-intuitive property of realloc() that it will do a malloc() if the pointer passed in is null. You can instead do a check on array->list == 0 and use malloc() then and realloc() otherwise. You might notice that this structure simplifies the calling code too; you no longer have to deal with the separate int *size; in the main program (and its memory allocation); the size is effectively bundled into the VertexList structure as num_inuse. The main program might now start: int main(void) { VertexList array; initVertexList(&array); addPointerToArray((Vertex){ 1, 1 }, &array); // C99 compound literal addPointerToArray((Vertex){ 2, 2 }, &array); addPointerToArray((Vertex){ 3, 3 }, &array); addPointerToArray((Vertex){ 9, 9 }, &array); for (int i = 0; i < array->num_inuse; i++) printf("Vertex %d: (%d, %d)\n", i, array->list[i].x, array->list[i].y, i); return 0; } (It is coincidental that this sequence will only invoke the memory allocation once because the new size (old_size + 2) * 2 allocates 4 elements to the array the first time. It is easy to exercise the reallocation by adding a new point, or by refining the formula to (old_size + 1) * 2, or ... If you plan to recover from memory allocation failure (rather than just exiting if it happens), then you should modify addPointerToArray() to return a status (successful, not successful). Also, the function name should probably be addPointToArray() or addVertexToArray() or even addVertexToList(). A: I have a few suggestions for your consideration: 1. Don't use the same input & output parameter while using realloc as it can return NULL in case memory allocation fails & the memory pointed previously is leaked. realloc may return new block of memory (Thanks to @Jonathan Leffler for pointing out, I had missed this out). You could change your code to something on these lines: Vertex * new_out = realloc(out, newSize * sizeof(Vertex)); if( NULL != new_out ) { out = new_out; out[(*size)] = v1; } else { //Error handling & freeing memory } 2. Add NULL checks for malloc calls & handle errors when memory fails. 3. Calls to free are missing. 4. Change the return type of addPointerToArray() from void to bool to indicate if the addition is successful. In case of realloc failure you can return failure say, false else you can return success say, true. Other observations related to excessive copies etc, are already pointed out by @MatthewD. And few good observations by @Jonathan Leffler (: Hope this helps! A: Your sample program works fine for me. I'm using gcc 4.1.1 on Linux. However, if your actual program is anything like your sample program, it is rather inefficient! For example, your program copies memory a lot: structure copies - initialising out, passing vertices to addPointerToArray(), memory copies via realloc(). Pass structures via a pointer rather than by copy. If you need to increase the size of your list type a lot, you might be better off using a linked list, a tree, or some other structure (depending on what sort of access you require later). If you simply have to have a vector type, a standard method of implementing dynamically-sized vectors is to allocate a block of memory (say, room for 16 vertices) and double its size everytime you run out of space. This will limit the number of required reallocs. A: Try these changes , it should work. void addPointerToArray(Vertex v1, Vertex (*out)[], int *size) { int newSize = *size; newSize++; *out = realloc(out, newSize * sizeof(Vertex)); *out[(*size)] = v1; // Update Size *size = newSize; } and call the function like addPointerToArray(vertexToAdd, &out, size); * *There is a simple way to fix these type of issue (you might already know this). When you pass a argument to a function, think what exactly goes on to the stack and then combine the fact that what ever changes you make to variables present on stack would vanish when come out the function. This thinking should solve most of the issues related to passing arguments. *Coming to the optimization part, picking the right data structure is critical to the success of any project. Like somebody pointed out above, link list is a better data structure for you than the array.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563308", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How can I have live info on a page without refreshing? Facebook has introduced a ticker which shows live news scrolling down. How can I have this same time of functionality on my site? I don't care to use an iframe and have it refresh because it will A flicker and B make the page loading icon come up (depending on browser). How can this be done? A: For this you'd want to fetch the data you're looking for with AJAX every X seconds.. Also known as polling. Here's the break down: Every X seconds, we want to query our database for new data. So we send an asychronous POST to a php page, which then returns a data set of the results. We also declare a callback function (native to jQuery) that will be passed the data echo'd from our PHP. Your PHP: if (isset($_POST['action'])){ if ($_POST['action'] == 'pollNewData'){ pollNewData(); } } function pollNewData(){ $term = $_POST['term']; $sql = "select * from TABLE where TERM = '$term'"; $result = get_rows($sql); echo json_encode(array('status'=>200, 'results'=>$results)); } Your front end javascript: setTimeout(pollForNewData, 10000); function pollForNewData(){ $.post('url/ajax.php',{ action: 'pollNewData', term: 'your_term' }, function(response){ if (response.status == 200){ $.each(response.results, function(index, value){ $("#container").append(value.nodeName); }); } }, 'json'); } What essentially is going on here is that you will be posting asynchronously with jQuery's ajax method. The way you trigger a function in your PHP would be by referencing a key-value item in your post depicting which function you want to call in your ajax request. I called this item "Acton", and it's value is the name of the function that will be called for this specific event. You then return your data fetched by your back end by echo'ing a json_encoded data set. In the javascript, you are posting to this php function every 10 seconds. The callback after the post is completed is the function(response) part, with the echo'd data passed as response. You can then treat this response as a json object (since after the function we declared the return type to be json. A: Pretty much the only way you can do it is with some sort of Asyncronous javascript function. The easiest way to do it is to have javascript priodically poll another http resource with that information and replace the current content in the dom with the new content. Jquery and other javascript frameworks provide AJAX wrappers to make this process reasonably simple. You aren't limited to using XML in the request. It's a good idea to make sure that even without javascript enabled that some content is available. Just use the javascript to 'update it' without having to refresh the page. A: You can do this kind of ticker using Ajax... using AJAX you can poll a URL that returns JSON/XML containing the new updates and once you get the data, you can update the DOM. you can refer this page for introduction to Ajax. A: Ajax is the best method but that's what everyone else already mentioned. I wanted to add that although I agree ajax is the best method, there are other means too, such as Flash. A: There are two approaches possible for obtaining updates like this. The first is called push and the second is called pull. With push updates, you rely on the server to tell the client when new information is available. In your example, a push update would come in the form of Facebook telling your site that something new happened. In general, push schemes will tend to be more bandwidth friendly because you only transmit information when something needs to be said (Facebook doesn't contact your site if nothing is going on). Unfortunately, push updating requires the server to be specially configured to support it. In other words, unless the service you are asking for updates from (ex. Facebook) has a push update service available to you, you cannot implement one yourself. That's where pull techniques come in. With pull updating, the client requests new information from the server when it deems necessary. It is typically implemented using polling such that the client will regularly and periodically query the server to see what the latest information is. Depending on how the service is oriented, you may have to do client-side parsing to determine if what you receive as a response is actually new. The downside here is of course that you likely will consume unnecessary amounts of bandwidth for your polling requests where no useful information is obtained. Similarly, you may not be as up-to-date with new information as you would like to be, depending on your polling interval. In the end, since your site is web-based and is interfacing with Facebook, you will likely want to use some sort of AJAX system. There are a few hybrid-ish approaches, such as long polling via Comet, which are outlined rather well on Wikipedia: Push technology: http://en.wikipedia.org/wiki/Push_technology Pull technology: http://en.wikipedia.org/wiki/Pull_technology
{ "language": "en", "url": "https://stackoverflow.com/questions/7563310", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to loop over histogram to get the color of the picture? In this answer about detecting the color of an image olooney said that "loop over the histogram and take the average of pixel color weighed by the pixel count". I ran the histogram like this: class ImageResize(webapp.RequestHandler): def get(self): q = HomePage.all() q.filter("firm_name", "noise") qTable = q.get() id = qTable.key().id() if id: homepage = HomePage.get_by_id(id) if homepage: img = images.Image(homepage.thumbnail) hist = img.histogram() then in IDLE, for each color of the histogram hist2, I tried to get the average and divided by pixel count, but I get the same number. What am I doing wrong? >>> average_red = float(sum(hist2[0]))/len(hist2[0]) >>> average_red 789.2578125 >>> average_green = float(sum(hist2[1]))/len(hist2[1]) >>> average_green 789.2578125 >>> average_blue = float(sum(hist2[2]))/len(hist2[2]) >>> average_blue 789.2578125 >>> Update Thanks to Saxon Druce for the answer. Here's the code I used: >>> def hist_weighed_average(hist): red_hist = hist[0] green_hist = hist[1] blue_hist = hist[2] red_weighed_sum = float(sum(i * red_hist[i] for i in range(len(red_hist)))) green_weighed_sum = float(sum(i * green_hist[i] for i in range(len(green_hist)))) blue_weighed_sum = float(sum(i * blue_hist[i] for i in range(len(blue_hist)))) red_num_pixels = float(sum(red_hist)) green_num_pixels = float(sum(green_hist)) blue_num_pixels = float(sum(blue_hist)) red_weighed_average = red_weighed_sum / num_pixels green_weighed_average = green_weighed_sum / num_pixels blue_weighed_average = blue_weighed_sum / num_pixels return red_weighed_average, green_weighed_average, blue_weighed_average >>> hist = hist3 >>> hist_weighed_average(hist) (4.4292897797574859, 4.8236723583271468, 5.2772779015095272) >>> hist = hist2 >>> hist_weighed_average(hist) (213.11471417965851, 220.01047265528334, 214.12880475129919) >>> A: Assuming hist2[0] is the histogram of the red pixels, then it is a histogram of pixel counts indexed by the red component. That means that sum(hist2[0]) is always going to be the number of pixels in the image, and len(hist2[0]) is always going to be 256. This will always give you the same answer, for all three of red, green and blue. You need to multiply the pixel counts (the values in the histogram) by the pixel values (the index in the list), then add them, to get a weighted sum. Then divide by the number of pixels to get the weighted average. Maybe something like this: red_hist = hist2[0] weighted_sum = sum(i * red_hist[i] for i in range(len(red_hist))) num_pixels = sum(red_hist) weighted_average = weighted_sum / num_pixels
{ "language": "en", "url": "https://stackoverflow.com/questions/7563315", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is this error in the code? while working in try-catch in came across this error. But I cant trace out the reason for this error though I surfed the net and SO. My code is... int main() { Queue q; int choice,data; while(1) { choice = getUserOption(); switch(choice) { case 1: cout<<"\nEnter an element:"; cin>>data; q.enqueue(data); break; case 2: int element; element = q.dequeue(); cout<<"Element Dequeued:\n"<<element; break; case 3: q.view(); break; case 4: exit(EXIT_SUCCESS); } catch(UnderFlowException e) { cout<<e.display(); } catch(OverFlowException e) { cout<<e.display(); } }// end of while(1) return 0; } For me everything in the above code seems to be correct. But g++ complier is throwing... muthu@muthu-G31M-ES2L:~/LangFiles/cppfiles/2ndYearLabException$ g++ ExceptionHandlingEdited.cpp ExceptionHandlingEdited.cpp: In member function ‘void Queue::enqueue(int)’: ExceptionHandlingEdited.cpp:89:97: warning: deprecated conversion from string constant to ‘char*’ ExceptionHandlingEdited.cpp: In member function ‘int Queue::dequeue()’: ExceptionHandlingEdited.cpp:113:95: warning: deprecated conversion from string constant to ‘char*’ ExceptionHandlingEdited.cpp: In member function ‘void Queue::view()’: ExceptionHandlingEdited.cpp:140:66: warning: deprecated conversion from string constant to ‘char*’ ExceptionHandlingEdited.cpp: In function ‘int main()’: ExceptionHandlingEdited.cpp:185:3: error: expected primary-expression before ‘catch’ ExceptionHandlingEdited.cpp:185:3: error: expected ‘;’ before ‘catch’ ExceptionHandlingEdited.cpp:189:3: error: expected primary-expression before ‘catch’ ExceptionHandlingEdited.cpp:189:3: error: expected ‘;’ before ‘catch’ A: You can't have a catch without a try. Put the line: try { before your while statement. If you want to get rid of the warnings about the string constants, you'll probably have to change the types to const char * or explicitly cast/copy them. Or you can use the -Wno-write-strings option to gcc. A: You need to surround your code in try {...} construct, otherwise catch will not know what code it should catch. Wrap your while loop into try: try { while(1) { ..... }// end of while(1) } catch(UnderFlowException e) ... Reference. A: Try this: int main() { Queue q; int choice,data; while(1) { choice = getUserOption(); try { switch(choice) { case 1: cout<<"\nEnter an element:"; cin>>data; q.enqueue(data); break; case 2: int element; element = q.dequeue(); cout<<"Element Dequeued:\n"<<element; break; case 3: q.view(); break; case 4: exit(EXIT_SUCCESS); } } catch(UnderFlowException e) { cout<<e.display(); } catch(OverFlowException e) { cout<<e.display(); } }// end of while(1) return 0; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7563319", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Loop two variables one is conditional on another one I want to make a loop which contains two variables i,j. for each i equals 1:24, j can be 1:24 but I don't know to make this loop; i=1 while(i<=24) { j=seq(1,24,by=1) for (j in j) { cor[i,j] } } i=i+1 is this right? my output is cor[i,j]. A: In order to accomplish your final goal try... cor(myMatrix) The result is a matrix containing all of the correlations of all of the columns in myMatrix. If you want to try to go about it the way you were it's probably best to generate a matrix of all of the possible combinations of your items using combn. Try combn(1:4,2) and see what it looks like for a small example. For your example with 24 columns the best way to cycle through all combinations using a for loop is... myMatrix <- matrix(rnorm(240), ncol = 24) myIndex <- combn(1:24,2) for(i in ncol(myIndex)){ temp <- cor(myMatrix[,myIndex[1,i]],myMatrix[,myIndex[2,i]]) print(c(myIndex[,i],temp)) } So, it's possible to do it with a for loop in R you'd never do it that way. (and this whole answer is based on a wild guess about what you're actually trying to accomplish because the question, and your comments, are very hard to figure out)
{ "language": "en", "url": "https://stackoverflow.com/questions/7563322", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to find MLS data? I often see the same real estate listings across many different websites. Is there a central place where websites get their data from? How can I find an API or XML feed or aomething with real estate listings for a certain area? A: Leonel, there are local Realtor Associations. They each operate their own database and MLS information. They then optionally share it with other groups like realtor.com, trulia.com, zilliw.com etc. But the data always goes to the local city/region Realtor association. There is IDX - limited data and VOW full data that Realtors can get feeds / data dumps for their website. Most of the local associations run systems that use the RETS interface to export data in a standard way. So you essentially need to contact the local association, and usually need to be a member of the association. You think it would be easy data to get, but it's actually pretty well guarded. Trulia worked hard to build the relationships to get the data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563323", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to save text file without overwriting? I want to save in a text file without overwriting the current data. I mean the next data that will be save will go to the new/next line whenever I save and that is my problem, I don't know how to do that. Could someone help me about this matter? Here's the code in save() method : public void save(String filename) throws IOException { FileOutputStream fOut = new FileOutputStream(filename); ObjectOutputStream outSt = new ObjectOutputStream(fOut); outSt.writeObject(this); } A: Read the docs public FileOutputStream(File file, boolean append) throws FileNotFoundException Creates a file output stream to write to the file represented by the specified File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning. A new FileDescriptor object is created to represent this file connection.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563327", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Add comment between continue line (underbar) on ASP Classic VBScript I am currently trying to figure out how to add comment within a line continuation statement on ASP classic. Our code management requirement requires us to write a Start block and End block to mark the place where we did a change. For example. Old code arrayName = Array("FIRST_NAME", _ ,"LAST_NAME" _ ,"ADDRESS" ) New code arrayName = Array("FIRST_NAME" _ ,"LAST_NAME" _ ,"ADDRESS" _ ' 2011/09/27 bob Added new column for XYZ support Start ,"NEW_COLUMN" _ ' 2011/09/27 bob Added new column for XYZ support End ) The new code is causing an error since the underbar cannot be placed within the comment. Are there anyway to place code management comment between such lines? Just want to see if I may have missed other options. I think there is none but what do you guys/gals think? A: Use this comment instead: ' 2011/09/27 bob Added "NEW_COLUMN" for XYZ support arrayName = Array("FIRST_NAME" _ ,"LAST_NAME" _ ,"ADDRESS" _ ,"NEW_COLUMN" _ ) Your version control system will take care of showing the differences so there's little use for the start and end comments. A: If the comment line position is very important for you, you may need to write your own array push procedure. So, you have not missed anything. This is the cause of VBScript syntax. With underscore, actually runs following: Array("FIRST_NAME", "LAST_NAME", "ADDRESS", 'comment, "NEW_COLUMN", 'comment) And this will cause an error too. I wrote this to giving idea about push into arrays. Sub [+](arrT, ByVal val) Dim iIdx : iIdx = 0 If IsArray(arrT) Then iIdx = UBound(arrT) + 1 ReDim Preserve arrT(iIdx) Else ReDim arrT(iIdx) End If arrT(iIdx) = val End Sub 'Start push [+]arrayName, "FIRST_NAME" [+]arrayName, "LAST_NAME" [+]arrayName, "ADDRESS" '2011/09/27 bob Added new column for XYZ support Start [+]arrayName, "NEW_COLUMN" '2011/09/27 bob Added new column for XYZ support End 'Test Response.Write Join(arrayName, "<br />")
{ "language": "en", "url": "https://stackoverflow.com/questions/7563329", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: C++ Saving/Loading a function as bytes. Getting the size of a function Ok so I've used function pointers for some time. I was trying to figure out if this was possible. First. It IS possible to convert a function pointer into an array of bytes. It is also possible to reconstruct that function with the bytes in that array. I would like to save a function into an array of bytes, and lets say save it to a text file (func.dat). Then later read that text file and execute the particular function... Is it possible? It seems it should be possible the only problem I run across is finding the size of the array that makes up the function. Is there any way to do this? int func() { return 1+1; } int main() { int (*foo)() = func; char* data = (char*)func; // write all the data char* copyFunc = new char[sizeof(func)]; for(int i = 0; i < sizeof(func); i++) copyFunc[i] = data[i]; int (*constructedFoo)() = (int (*)())copyFunc; return 0; } of course this code won't compile because sizeof does not work for functions, does anyone know how to get the size of a function? Or the size of the function header/footer. I have tried things like int func() { 1+1; new char('}'); } Then searched for the } char (as the end of the function) but that size doesn't work. If your wondering why I need it, it could be used for lets say, sending a function to a remote computer to execute (thinking of parallel processing) Or even saving a function in a file like in my first example to later be used, this can be helpful. Any help is greatly appreciated. A: What you're trying to do is not possible in C/C++. First of all, functions may not be contiguous in memory in the binary. So there's no definite "size". Secondly, you can't just load it into another program and execute it because it will violate memory protection (among other things, like address space). Lastly (if you managed to get this far), all non-relative jumps and references in the function will likely be broken. EDIT: The way to go about sending code to remote computers is to send entire (compiled) binaries. Then have the local and remote machines communicate. A: Well there is actually a way how to save and load bytes of code and even run them. This is a great arcicle about that: http://www.codeproject.com/KB/tips/Self-generating-code.aspx?msg=2633508#xx2633508xx A: One thing you can do if you want dynamically loaded functions: * *Create a dynamic library containing your functions (.dll or .so) *Export those symbols with extern "C" and if necessary declspec(dllexport) *Load the library at runtime with LoadLibrary() or dlopen() *Extract a particular symbol with GetProcAddress() or dlsym() *Execute it with libffi. *Clean up after yourself with FreeLibrary() or dlclose()
{ "language": "en", "url": "https://stackoverflow.com/questions/7563332", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Multiple Zend framework sites on one server I'm having trouble setting up my httpd.conf or .htaccess files to recognize multiple zend framework sites on one server. For development, I have just one server and I'm trying to setup the sites so I can access them like localhost/app1, localhost/app2, etc. So right now, when I go to localhost/app1 it does successfully redirect to localhost/app1/public/index.php, however when I go to localhost/app1/index/index I get a 404. Here is my vhosts file: <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot "/var/www" <Directory /> Options FollowSymLinks AllowOverride None </Directory> <Directory "/var/www/app1/public"> Options Indexes FollowSymLinks MultiViews AllowOverride All Order allow,deny allow from all </Directory> ErrorLog logs/error.log CustomLog logs/access.log common </VirtualHost> and here is my .htaccess file from the /var/www/app1 directory: RewriteEngine On RewriteCond %{REQUEST_FILENAME} -s [OR] RewriteCond %{REQUEST_FILENAME} -l [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^.*$ /app1/public/index.php [NC,R,L] If I change the DocumentRoot line in the vhosts file to DocumentRoot "/var/www/app1/public" then app1 does work correctly, but I can only access that one... at http://localhost. Is this possible? What I want to happen is if /var/www is the document root, then if I go to localhost/app1, those requests need to redirect to localhost/app1/public/index.php and if I go to localhost/app2 those requests need to redirect to localhost/app2/public/index.php. I hope I explained this clearly, any help is appreciated. In the end I liked Phil's solution best because I didn't want to have to change my local hosts file and use the ServerName directive. It would be fine in a production environment if you own a separate domain name for each app, but not for development. In addition to that, I was having a 403 forbidden problem when using an alternate directory for serving up web content. As I stated, the perms seemed correct the problem was with SE_Linux, and the security context of the files not being set to httpd_sys_content_t. I'm posting that solution that i found here, as it deals specifically with the issue. Thanks. A: Here's what I'd do... * *Install your applications somewhere arbitrary but outside the document root, eg /home/sudol/apps/app1 and /home/sudol/apps/app2. Make sure your Apache user can traverse this path and read the files. *Alias the public directories in your <VirtualHost> section Alias /app1 /home/sudol/apps/app1/public Alias /app2 /home/sudol/apps/app2/public *Setup your access and rewrite rules in the appropriate <Directory> sections (one for each app), eg <Directory "/home/sudol/apps/app1/public"> Options Indexes FollowSymLinks MultiViews AllowOverride All Order allow,deny allow from all RewriteEngine On RewriteBase /app1 RewriteCond %{REQUEST_FILENAME} -s [OR] RewriteCond %{REQUEST_FILENAME} -l [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^.*$ - [NC,L] RewriteRule ^.*$ index.php [NC,L] </Directory> *Delete the .htaccess files as you will no longer need them Addendum Make sure you set unique session names in your application config. You can also set specific cookie paths but this is optional, eg ; app1/application/configs/application.ini resources.session.name = "app1" resources.session.cookie_path = "/app1/" ; app2/application/configs/application.ini resources.session.name = "app2" resources.session.cookie_path = "/app2/" A: Its better to use subdomain i.e app1.localhost then localhost/app1 . Since the way cookies are stored (including session cookie) can give you problem latter . They will mismatch or can even overlap . Here is a good tutorial to setup the preferred way http://www.dennisplucinik.com/blog/2007/08/16/setting-up-multiple-virtual-hosts-in-wamp/
{ "language": "en", "url": "https://stackoverflow.com/questions/7563333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: "Unrecognized Windows Sockets error: 0: JVM_Bind" when trying to debug in Flash Builder 4.5 for PHP Im trying to debug an app, not server related yet, with the new version of the FB, the one that comes with Zend in it. Thing is, everytime I try to debug, the message error is the same: "Unrecognized Windows Sockets error: 0: JVM_Bind" Do any of you have an idea about this? Thanks in advance. A: Check your ports JVM_Bind means the server socket could not connect to that port as its already being used by another server socket netstat (with -b param ) should tell you the ports being used and the exe that started listening on it make sure it is not being used A: * *Close other programs or services that could open ports. *Check mm.cfg file content c:\Users{Username}\mm.cfg for Win7. There could be strange settings for profiler. Actually you can remove this file to reset debug setting (with backup!). I afraid that zend debugger could bind to the same port.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563336", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Drupal Display Modified Date for Node Is there a simple way in Drupal to display the last modified date for a node as part of the node.tpl.php file? A: If you put this code in the node.tpl.php file it will show the date of the last change to the node: <?php echo format_date($node->changed); ?> with whatever HTML you want around it. A: If you place below code in you node.tpl.php file - <?php $node = node_load($nid); echo $node->changed; ?> you will get the timestamp and i think that can be changed to date. Here $nid in tpl file represent the current node id, and hook node_load() load the all information related to node id. A: No need to edit node.tpl.php file. Use the following in template.php. function sitetheme_preprocess_node(&$variables) { $node = $variables['node']; // Only add the revision information if the node is configured to display if ($variables['display_submitted'] && ($node->revision_uid != $node->uid || $node->revision_timestamp != $node->created)) { // Append the revision information to the submitted by text. $revision_account = user_load($node->revision_uid); $variables['revision_name'] = theme('username', array('account' => $revision_account)); $variables['revision_date'] = format_date($node->changed); $variables['submitted'] .= t(' and last modified by !revision-name on !revision-date', array( '!name' => $variables['name'], '!date' => $variables['date'], '!revision-name' => $variables['revision_name'], '!revision-date' => $variables['revision_date'])); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7563340", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Upload a Cover (PHP) Anybody know how to upload a profile cover? Not a Album cover but a profile cover for the new timeline? Any help is much appreciated. A: Maybe Facebook will roll out a specific API for that in the future, but so far the only way is to upload the photo via the photo API and then ask the user to choose it as his cover... To upload a photo use a HTTP POST to https://graph.facebook.com/ALBUM_ID/photos (as seen on http://developers.facebook.com/docs/reference/api/) A: There's no API for this just yet.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563343", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I increase the bullet size in a li? The bullets in IE8 are so small, I tried changing the font-size, but that didn't work. Code: <ul style="padding:0; margin:0; margin-left:20px;"> <li>item 1</li> <li>item 2</li> </ul> Is there any way to do this without using an image for the bullet? A: You could do this in an IE8 conditional comment... ul { list-style: none; } ul li:before { content: "•"; font-size: 170%; /* or whatever */ padding-right: 5px; } jsFiddle. In IE7, you could prepend the bullet via JavaScript and style it accordingly. A: You can also do: li::marker{ content:"\25A0"; font-size: 1.5rem; color: black; vertical-align: bottom; } A: Internet Explorer doesn't seem to natively support sizing of the bullets from list-style-type with font-size as Firefox and Chrome appear to. I do not know if this is a known problem or bug. There are workarounds, but sometimes an image is the quickest and more widely supported "fix". A: IE8+ does scale the bullets but not for every font size. My fix is based on the fact the bullets for Verdana are larger than for Arial. I use css to set Verdana for li, at the same time I add extra spans around li's contents to keep the original font. Also, as Verdana can makes the lines higher, I may need to use line-height to make up for that, but that depends on the browser. Also I can use bigger font size for li to make the bullets even larger, then I'll have to use still smaller line-height. ul { font: 12px Arial; } ul li { font-family: Verdana; line-height: 120%; } /* font-size: 14px; line-height: 100%; */ ul li span { font: 12px Arial; } <ul> <li><span>item 1</span> <li><span>item 2</span> </ul>
{ "language": "en", "url": "https://stackoverflow.com/questions/7563344", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "30" }
Q: Making sure a file path is complete in grep I had to change the path of my template directory and I want to make sure all my files refer to "templates/app/xxx.html" instead of "templates/xxx.html" How can I use grep to see all lines of "*.html", but not "app/*.html"? A: Assuming there's only one per line, you could start with something like: grep '\.html' | grep -v '/app/.*\.html' The first will deliver all those that have .html. The second will strip from that list all those that have the app variant, leaving only those that violate your check. Obviously, this may need to be adjusted depending on how tricky your lines are (more than one per line, other stuff on the line and so forth) but this "give me a list of all possible violations then remove those that aren't violations" is a tried and tested method. For example (as Kent suggests), you may want to ensure that the HTML files are all directly in the app directories instead of possibly app/something/xyzzy.html. In that case, you could simply adjust your second filter to ensure this: grep '\.html' | grep -v '/app/[^/]*\.html' Using [^/]* (any number of non-/ characters) instead of .* (any number of characters, including /) will leave in those that don't have the HTML file directly in the app directory. A: It might also be useful to know which files contained unwanted references to the old path. I'd do something like this (disclaimer: not tested! But I copied some of it from paxdiablo, so that part's probably right.) find /path/to/files_to_check -type f -name "*.html" -exec grep '\.html' {} \; /dev/null | grep -v '/app/.*\.html' The find command searches a directory hierarchy for regular files with names ending in .html. Adjust as necessary for your situation. For each of these files, grep is run with two file arguments: {} representing the target path, and /dev/null to get grep to prefix the matching line with the filename it occurred in. From that, we strip out anything matching '/app/.*\.html'. What's left is a list of lines that need to be fixed, along with the filenames where they were found. A: or use this grep -P '(?<!/app)/[^/]*\.html test: kent$ echo ".../app/a/b/x.html .../foo/myapp/y.html .../foo/app/z.html"|grep -P '(?<!/app)/[^/]*\.html' .../app/a/b/x.html .../foo/myapp/y.html note that this will ignore ..../app/*.html, but .../myapp/*.html or .../app/foo/x.html will be matched.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563345", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: php json encode problem In order to access this data via ajax, how can I give each json encoded value a constant name? $data = array(); foreach($query->result() as $row) { $data[$row->id] = $row->name; } This returns json in this format: {"12428":"Alpine 12\" Single-Voice-Coil 4-Ohm Subwoofer",} The id (12428) is not constant and therefore, I have nothing constant to look for when trying to decode the data with ajax. How can I change the php code to add a constant value foreach of the encoded json items? A: $data = Array(); foreach($query->result() as $row) { $data[] = Array("id" => $row->id, "name" => $row->name); } Then, your JSON object looks like: [{"id":"12428","name","Alpine 12\" Single-Voice-Coil 4-Ohm Subwoofer"}] You can now loop through that array and get the id and name of each element. A: Who cares. js> d = {"12428":"Alpine 12\" Single-Voice-Coil 4-Ohm Subwoofer"} [object Object] js> for (i in d) { print(d[i]); } Alpine 12" Single-Voice-Coil 4-Ohm Subwoofer
{ "language": "en", "url": "https://stackoverflow.com/questions/7563347", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Type mismatch in key from map when replacing Mapper with MultithreadMapper I'd like to implement a MultithreadMapper for my MapReduce job. For this I replaced Mapper with MultithreadMapper in a working code. Here's the exeption I'm getting: java.io.IOException: Type mismatch in key from map: expected org.apache.hadoop.io.IntWritable, recieved org.apache.hadoop.io.LongWritable at org.apache.hadoop.mapred.MapTask$MapOutputBuffer.collect(MapTask.java:862) at org.apache.hadoop.mapred.MapTask$NewOutputCollector.write(MapTask.java:549) at org.apache.hadoop.mapreduce.TaskInputOutputContext.write(TaskInputOutputContext.java:80) at org.apache.hadoop.mapreduce.lib.map.MultithreadedMapper$SubMapRecordWriter.write(MultithreadedMapper.java:211) at org.apache.hadoop.mapreduce.TaskInputOutputContext.write(TaskInputOutputContext.java:80) at org.apache.hadoop.mapreduce.Mapper.map(Mapper.java:124) at org.apache.hadoop.mapreduce.Mapper.run(Mapper.java:144) at org.apache.hadoop.mapreduce.lib.map.MultithreadedMapper$MapRunner.run(MultithreadedMapper.java:264) Here's the code setup: public static void main(String[] args) { try { if (args.length != 2) { System.err.println("Usage: MapReduceMain <input path> <output path>"); System.exit(123); } Job job = new Job(); job.setJarByClass(MapReduceMain.class); job.setInputFormatClass(TextInputFormat.class); FileSystem fs = FileSystem.get(URI.create(args[0]), job.getConfiguration()); FileStatus[] files = fs.listStatus(new Path(args[0])); for(FileStatus sfs:files){ FileInputFormat.addInputPath(job, sfs.getPath()); } FileOutputFormat.setOutputPath(job, new Path(args[1])); job.setMapperClass(MyMultithreadMapper.class); job.setReducerClass(MyReducer.class); MultithreadedMapper.setNumberOfThreads(job, MyMultithreadMapper.nThreads); job.setOutputKeyClass(IntWritable.class); job.setOutputValueClass(MyPage.class); job.setOutputFormatClass(SequenceFileOutputFormat.class);//write the result as sequential file System.exit(job.waitForCompletion(true) ? 0 : 1); } catch (Exception e) { e.printStackTrace(); } } And here's the mapper's code: public class MyMultithreadMapper extends MultithreadedMapper<LongWritable, Text, IntWritable, MyPage> { ConcurrentLinkedQueue<MyScraper> scrapers = new ConcurrentLinkedQueue<MyScraper>(); public static final int nThreads = 5; public MyMultithreadMapper() { for (int i = 0; i < nThreads; i++) { scrapers.add(new MyScraper()); } } public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { MyScraper scraper = scrapers.poll(); MyPage result = null; for (int i = 0; i < 10; i++) { try { result = scraper.scrapPage(value.toString(), true); break; } catch (Exception e) { e.printStackTrace(); } } if (result == null) { result = new MyPage(); result.setUrl(key.toString()); } context.write(new IntWritable(result.getUrl().hashCode()), result); scrapers.add(scraper); } Why the hell am I getting this? A: Here's what has to be done: MultithreadedMapper.setMapperClass(job, MyMapper.class); MyMapper must implement the map logic MultithreadMapper must be empty
{ "language": "en", "url": "https://stackoverflow.com/questions/7563353", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: xslt - can't access curent node with attribute selector I am trying to transform an xml file with xsl stylesheet into html. this is the java TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(new StreamSource(classLoader.getResourceAsStream("driving.xsl"))); StreamResult drivingHtml = new StreamResult(new StringWriter()); transformer.transform(new StreamSource(classLoader.getResourceAsStream("driving.xml")), drivingHtml); System.out.println(drivingHtml.getWriter().toString()); this is some of the xml: <?xml version="1.0" encoding="UTF-8"?> <user xmlns="http://notreal.org/ns1" xmlns:poi="http://notreal2.org/ns2"> <address type="primary"> <street>1031 Court St.</street> <city>Monhegan, NY</city> </address> <address type="secondary"> <street> Elm St.</street> </address> this is the xsl: <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <html> <head> <title>User</title> </head> <body> <p>Detailed Addresses</p> <table> <th>Primary</th> <th>Secondary</th> <tr> <xsl:apply-templates select="/user/address"/> </tr> </table> </body> </html> </xsl:template> <xsl:template match="address"> <td> <xsl:value-of select=".[@type='primary']/street" /> <xsl:value-of select=".[@type='secondary']/street" /> </td> <td> <xsl:value-of select=".[@type='primary']/city" /> <xsl:value-of select=".[@type='secondary']/city" /> </td> </xsl:template> </xsl:stylesheet> when i run that, i get "cannot compile stylesheet" A: Your main problem, based on the XML and XSLT code provided, is that your code doesn't address at all the fact that the elements in the XML document are in a default namespace. How to process an XML document with a default namespace is a FAQ -- just search the xslt and xpath tags and you'll find numerous good answers. Here is one possible solution: This transformation: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:x="http://notreal.org/ns1" exclude-result-prefixes="x"> <xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/> <xsl:template match="/*"> <html> <head> <title>User</title> </head> <body> <p>Detailed Addresses</p> <table> <thead> <xsl:apply-templates select="x:address/@type"/> </thead> <tr> <xsl:apply-templates select="x:address/x:street"/> </tr> <tr> <xsl:apply-templates select="x:address/x:city"/> </tr> </table> </body> </html> </xsl:template> <xsl:template match="@type"> <th><xsl:value-of select="."/></th> </xsl:template> <xsl:template match="x:address/*"> <td><xsl:value-of select="."/></td> </xsl:template> </xsl:stylesheet> when applied on a complete and well-formed XML document that includes the XML fragment provided in the question: <user xmlns="http://notreal.org/ns1" xmlns:poi="http://notreal2.org/ns2"> <address type="primary"> <street>1031 Court St.</street> <city>Monhegan, NY</city> </address> <address type="secondary"> <street>203 Elm St.</street> <city>Pittsburgh, PA</city> </address> </user> produces (what seems to be) the wanted, correct result: <html> <head> <title>User</title> </head> <body> <p>Detailed Addresses</p> <table> <thead> <th>primary</th> <th>secondary</th> </thead> <tr> <td>1031 Court St.</td> <td>203 Elm St.</td> </tr> <tr> <td>Monhegan, NY</td> <td>Pittsburgh, PA</td> </tr> </table> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/7563354", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: RegularExpression - Positive Integer with 1 Decimal Point I can't seem to get the syntax correct for a RegularExpression using C# to only allow positive numbers with up to 1 decimal point. I have the following DataAnnotation for positive integers working: [RegularExpression(@"[^\-][\d\.]*", ErrorMessage = "Positive integers only")] Any tips? A: You want ^\d+(\.\d)?$. A: [RegularExpression(@"^\d+(\.\d)?$", ErrorMessage = "Positive integers only")] A: I propose ^(0|[1-9]\d*(\.\d)?)$. That way you also rule out things like 0001. A: You may try @"^\d+([.]\d?)?$"The "." is a special character and has to be escaped, otherwise the answer by SLaks is alright.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563355", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CSS in ajax-loaded content is not applied Sorry if this is obvious but I just don't know what more to do. I am using fancybox jQuery plugin to load html content into a modal, but the content doesn't show the css styles of the main document. CSS rules are called in the main document AND inside the loaded html in a <style> tag, but nothing. How can I fix this without having to apply individually each element's css with jQuery .css() calls? Thank you Note: I know this may be over-duplicated, but I still haven't found the right solution. Edit: Ajax-loaded content is inside an iframe A: Since, as you mention in the comments, you're actually loading content into an iframe, this loaded content will not be affected by styles in the container document. They're two distinct HTML pages, despite the illusion created by the iframe. Your best bet is to configure the content you're loading to use the same set of styles and style sheets as the container document, or a subset thereof. Treat it like just another HTML page on your site.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563357", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to make code run only if an exception was thrown? I have a try with several different catches after it. I have some "cleanup" code that only should be run if there was an exception thrown. I could add the same code to each exception, but that becomes a maintenance nightmare. Basically, I'd like something like the finally statement, but for it to only run if an exception was thrown. Is this possible? A: There is no direct support for this unfortunately. How about something like this boolean successful = false; try { // do stuff successful = true; } catch (...) { ... } finally { if (!successful) { // cleanup } } A: The only thing I can think of is to set a variable in each catch and then check for that variable in finally. Pseudocode: Boolean caught = false; try { //risky code here catch(err) { caught = true; // Do other stuff } catch(err) { caught = true; // Do other stuff } catch(err) { caught = true; // Do other stuff } finally { if (caught) { // Do clean up } } A: I could add the same code to each exception, but that becomes a maintenance nightmare. Or if you blot out the 'exception': I could add the same code to each [place], but that becomes a maintenance nightmare. This is what methods are made for. private void cleanup() { /* clean up */ } ... try { // oh noes } catch (MyException me) { cleanup(); } catch (AnotherException ae) { cleanup(); } Maintenance hassle gone! A: Why don't you just use simple try & catch? try { foo(); } catch(Exception1 e1) { dealWithError(1); } catch(Exception2 e2) { dealWithError(2); } catch(Exception3 e3) { dealWithError(3); } ... private void dealWithError(int i) { if(i == 1) // deal with Exception1 else if(i == 2) // deal with Exception2 else if(i == 3) // deal with Exception3 } A: You could try wrapping two layers of exception handlers, and rethrow the exception after you have done the common handling: try { try { // your code goes here } catch (Throwable t) { // do common exception handling for any exception throw t; } } catch (NullPointerException nx) { // handle NPE } catch (Throwable t) { // handle any other exception } Not sure I really like this solution though... feels like a bit of a hack. I'd probably rather see the Exception explicitly handled in each instance, even if this means repeating a call to some kind of shared cleanup function.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563365", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: including c++ libraries in ios programming I'm developing an ios app that's very basic and uses objective almost all of the time. However my app needs to deal with big integer numbers (eg: 2^200) and add and multiply them. To achieve that I need to include a c++ library called bigint that allows these operations on huge integers. The problem I have is that when I include the bigint project I get many errors and I thought that this could be because it's c++ and can't mix with objective c. I'm new to this idea and was wondering if there are any steps i need to take to correctly add a c++ library to an objective c project. By the way I'm not using opengl or anything complicated just simple ui and some quartz stuff. Update: I did everything you guys said, I changed all the extensions to .mm and added the bigint library. My project ran perfectly without errors before doing these things. I get an error when i do this and I get an error even if I don't even add the library. just changing the file extensions to .mm gives me the following error. This just doesnt make sense since everything ran fine before and I don't have any duplicates in my program. I have no idea why just changing the extensions to .mm could cause this error. Any ideas guys? A: You can mix in C++ files, but use a .cpp suffix for them (and .hpp for their corresponding header files). If you want to mix C++ and Obj-C in the same file, you can do that, but give it a .mm suffix.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563367", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Extract Multiple Strings from Paragraph How do I extract more than one email from a paragraph and output the result to a console? var pattern:RegExp = (/^\b[-._0-9a-zA-Z]+@[-._0-9a-zA-Z]+[\.]{1}[0-9a-zA-Z]+[\.]?[0-9a-zA-Z]\b$/i); var asd:String; asd=tt.text; trace(asd.match(pattern)); A: Try this regex pattern instead: ([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9}) A: You need to add a g to the end of your RegExp pattern to make it a global search, and hence return all the matches, which will be returned in an Array. Eg., var pattern:RegExp = (/foo/g); BTW, Grant Skinner has a great Flex/AIR app to develop and test regex patterns: Online Version
{ "language": "en", "url": "https://stackoverflow.com/questions/7563372", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Login to Provisioning Portal using XCode hope someone is able to help me with this. I am trying to use automatic provisioning through xcode's organizer. Whenever I click on it, it prompts me to log in to the developer portal. I entered my credentials but it keeps popping up, as though my credentials are incorrect. I have checked that my credentials are correct because I am able to log in to the portal through the website. Does anyone have a solution to this?
{ "language": "en", "url": "https://stackoverflow.com/questions/7563375", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Chrome extension: load different content scripts I want to load a different content script depending on the page and tab that is currently selected. Right now, I have three content scripts. I want to use two of them for one page and the third one for another page. Belonging to page 1: content_script.js load_content_script.js Belonging to page2: newtab_content_script.js right now my manifest looks like this { "name": "A plugin for AdData express. Generate an instant excel document from the brands you check mark.", "version": "1.0", "background_page": "background.html", "permissions": [ "cookies", "tabs", "http://*/*", "https://", "*", "http://*/*", "https://*/*", "http://www.addataexpress.com", "http://www.addataexpress.com/*" ], "content_scripts": [ { "matches": ["<all_urls>","http://*/*","https://*/*"], "js": ["load_content_script.js", "content_script.js", "newtab_content_script.js", "jquery.min.js", "json.js"] } ], "browser_action": { "name": "AdData Express Plugin", "default_icon": "icon.png", "js": "jquery.min.js", "popup": "popup.html" } } how would I structure this in the manifest or elsewhere? A: you should use Programmatic injection chrome.tabs.executeScript(null, {file: "content_script.js"}); A: Rather than using content scripts that are bound to URL expressions specified in the manifest, you should use executeScript, which lets you programmatically decide when to inject a JS snippet or file: // background.js chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => { // there are other status stages you may prefer to inject after if (changeInfo.status === "complete") { const url = new URL(tab.url); if (url.hostname === "www.stackoverflow.com") { // this is the line which injects the script chrome.tabs.executeScript(tabId, {file: "content_script.js"}); } } }); Make sure to add tabs permission to manifest.json: { // ...settings omitted... "permissions": [ "tabs", // add me ] } A: Just in the interest of completeness, the way you'd do this from the manifest is to have as many matches blocks under "content_scripts" as needed: "content_scripts": [ { "matches": ["http://www.google.com/*"], "css": ["mygooglestyles.css"], "js": ["jquery.js", "mygooglescript.js"] }, { "matches": ["http://www.yahoo.com/*"], "css": ["myyahoostyles.css"], "js": ["jquery.js", "myyahooscript.js"] } ],
{ "language": "en", "url": "https://stackoverflow.com/questions/7563379", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "25" }
Q: Convert range to string in VBA I need help converting a range to a usable string. I'm not 100% sure of what I need, because I have little VBA or VB.NET experience, but ultimately i want to take a bunch of cells like B32 to J52 and perform linest function on C-J (as y values) and B (as x value). I think if I can learn to pop out a string that says "Bxx:Jyy" Then i'd be able to tell it do linest(Cxx:Cyy, Bxx:Byy, true, false). Is there an easier way to do this? Anyway, all I have right now is some code to get the range from the user (just got it from Google). If someone could just help me get the string like stated above, I think I can manage the rest. Dim oRangeSelected As Range Set oRangeSelected = Application.InputBox("Please select a range of cells!", _ "SelectARAnge Demo", Selection.Address, , , , , 8) A: In this case you want the user selected range (not pre-existing selection), so MsgBox oRangeSelected.Address [Update] Actually, reading your question more closely, you can use ranges as is with LINEST, ie this sub gets a user range for X and Y and then feeds LINEST. The results are stored in an array, MyArr, which can be returned to the user. Sub Sample() Dim oRangeSelected1 As Range Dim oRangeSelected2 As Range Dim myArr() Set oRangeSelected1 = Application.InputBox("Please select a X range of cells!", "Select X Demo", Selection.Address, Type:=8) Set oRangeSelected2 = Application.InputBox("Please select a Y range of cells!", "Select Y Demo", , Type:=8) If oRangeSelected1.Columns.Count + oRangeSelected2.Columns.Count > 2 Then MsgBox "Please select a single column range only" Exit Sub End If If oRangeSelected1.Cells.Count <> oRangeSelected2.Cells.Count Then MsgBox "Ranges are of different length" Exit Sub End If myArr = Application.WorksheetFunction.LinEst(oRangeSelected1, oRangeSelected2) MsgBox "slope is " & Format(myArr(1), "0.00") & " & intercept is " & Format(myArr(2), "0.00") End Sub A: If you use Selected.Address that will display your range as a string.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563381", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WebSockets draft hixie 76 protocol for iOS I'm building a client on iPhone to connect to one server using WebSockets draft hixie 76 protocol. I already tried UnittWebSocketClient, but they don't have support for that protocol. Does anyone know any library that supports that protocol on iPhone? It could be Objective-C, C or C++. A: The version in SVN of the UnittWebSocketClient should work with hixie76 servers. Use the WebSocket00.h header. Let me know if you have difficulties. You can refer to the UnittWebSocketClient00Tests for sample code. Make sure you look in the SVN trunk and not the libraries available for download on the website.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563382", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: using a protocol & delegate to pass data between views I have almost finished working my way through this tutorial here Its really informative and has helped me understand how protocols and delegates work together for passing data around. However I have one warning that poping up when I try to tell my subview that the mainview is its delegate. its sending back this warning "+setDelegate:' not found (return type defaults to 'id')" Everything was on track up till that point and I am just woundering what this error means and if it is anything to do with the way I have implemented my code. below is where the warning is happening... - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { // Navigation logic may go here. Create and push another view controller. //--- Idendify selected indexPath (section/row) if (indexPath.section == 0) { //--- Get the subview ready for use VehicleResultViewController *vehicleResultViewController = [[VehicleResultViewController alloc] initWithNibName:@"VehicleResultViewController" bundle:nil]; // ... //--- Sets the back button for the new view that loads self.navigationItem.backBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Back" style: UIBarButtonItemStyleBordered target:nil action:nil] autorelease]; // Pass the selected object to the new view controller. [self.navigationController pushViewController:vehicleResultViewController animated:YES]; [VehicleResultViewController setDelegate:self]; //<<-- warning here says -->> Method'+setDelegate:' not found (return type defaults to 'id') switch (indexPath.row) { case 0: vehicleResultViewController.title = @"Manufacture"; [vehicleResultViewController setRequestString:@"manufacture.php"]; //sets the request string in searchResultsViewController break; //... Any help would be greatly appreciated. Updated, this is how I set my delegate up SecondView.h //... @interface VehicleResultViewController : UITableViewController <NSXMLParserDelegate> { //.. id <PassSearchData> delegate; } //.. @property (retain) id delegate; @end SecondView.m //.. @synthesize delegate; //.. - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; [[self delegate] setVehicleSearchFields:vehicleCellTextLabel]; } //.. I hope this better clarifies what I am doing. A: You are calling an instance method on a class. This line: [VehicleResultViewController setDelegate:self]; should be: [vehicleResultViewController setDelegate:self]; The first line calls setDelegate on VehicleResultViewController, which is the name of the class. Since setDelegate is not a class method the compiler complains. The corrected line calls setDelegate on vehicleResultViewController, which is an instance of the class that you allocated. This will work because setDelegate is an instance method. A: It seems that you have declared a setter for delegate as a class method, indicated by the + in the warning. I'm guessing you have this declared somewhere... + (void)setDelegate:(id <SomeProtocol>)aDelegate when it should be - (void)setDelegate:(id <SomeProtocol>)aDelegate
{ "language": "en", "url": "https://stackoverflow.com/questions/7563384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Codeigniter Change loaded language Currently i have a language loaded inside MY_Controller which extends CI_Controller. But inside a special page which controller (let's call it ABC controller) extends MY_Controller, I need to override the loaded language with another language. I tried loading another language inside this ABC controller, but unsuccessful. Is there a way to unload the loaded language and load another language? A: I know it's a bit late to answer this but I think you can change the config item 'language' dynamically based on page requirement. $this->config->set_item('language', 'chinese'); $this->config->set_item('language', 'english'); // based on the language folder of course holding language files I had a requirement to send newsletters in users base lang, and this helped me change the language on the fly, hope this might help.. A: Have you tried just loading the language file you need? $this->lang->load('filename', 'language'); It should be then accessible just like your default language. I haven't tested this tho, but from my understanding this should be the way to go about it. Reference: http://codeigniter.com/user_guide/libraries/language.html REVISED I ended up digging a bit more for you, and found that you CANNOT load a default language (define it as default in your controller) and then later try to change it to something else. Follow these steps: * *If you need a language OTHER than english (default), set that in your config. *If you want to load ANOTHER language on a controller basis, you need to define that (most commonly in your constructor using something like session array / user selection. *You cannot load 2 languages (1 in the constructor, then another in a different class.. won't work!) Reference here per forum posts: http://codeigniter.com/forums/viewthread/176223/ A: I encounter this problem and find a tricky solution. $this->lang->load('text', 'english'); echo $this->lang->line('__YOUR_LANG_VARIABLE__'); //CI will record your lang file is loaded, unset it and then you will able to load another //unset the lang file to allow the loading of another file if(isset($this->lang->is_loaded)){ for($i=0; $i<=sizeof($this->lang->is_loaded); $i++){ unset($this->lang->is_loaded[$i]); } } $this->lang->load('text', 'chinese'); echo $this->lang->line('__YOUR_LANG_VARIABLE__'); Hope it helps. A: an easier way is to reset the language data and is_loaded $this->lang->is_loaded = array(); $this->lang->language = array(); A: If you have any application installed built in codeigniter and you want add a language pack, just follow these steps: * *Add language files in folder application/language/arabic (I added arabic lang in sma2 built in ci) *Go to the file named setting.php In application/modules/settings/views/setting.php you will find the array: <div class="controls"> <?php /* $lang = array ( 'english' => 'English', 'arabic' => 'Arabic', // +++ Add this line 'spanish' => 'Español' Now save and run the application.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563390", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How do I check if a user has enabled a network regardless of whether or not that network is connected? All I want to do is see if the network is actually enabled (whether or not there is a check by the option in the settings menu). How do I go about doing this? To be specific: I got Wifi through WifiManager... ...and everything else has been a nightmare with everything else (specifically mobile data). This is how I'm trying with Mobile Data and WiMax: cm.getNetworkInfo(cm.TYPE_WIMAX).getDetailedState(); cm.getNetworkInfo(cm.TYPE_MOBILE).getDetailedState(); But those return DISCONNECTED when they are disabled or actually disconnected. EDIT: I found it: http://developer.android.com/reference/android/provider/Settings.System.html EDIT again: This doesn't really have what I want either... I will keep searching, though! A: NetworkInfo info = connectivityManager.getActiveNetworkInfo(); boolean isNetworkEnabled = (info == null ? false : true); A: Were you thinking of implementing these two methods from LocationListener: onProviderEnabled(), onProviderDisabled()? However, I think requestLocationUpdates() must be called first before with the listener before these methods will be called. A: public static boolean checkConnection(Context context) { ConnectivityManager connMgr = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); android.net.NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); android.net.NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if (wifi.isAvailable() && wifi.isConnected()) { status = true; } if (mobile.isAvailable() && mobile.isConnected()) { status = true; } else { status = false; } return status; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7563394", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: wxPython: global hotkey loop toggle I'm trying to create a hotkey toggle(f12) that will turn on a loop when pressed once then turn that loop off when pressed again. The loop is a mouse click every .5 seconds when toggled on. I found a recipe for a hot keys on the wxpython site and I can get the loop to turn on but can't figure a way to get it to turn off. I tried created a separate key to turn it off without success. The mouse module simulates 1 left mouse click. Here's my current code: import wx, win32con, mouse from time import sleep class Frameclass(wx.Frame): def __init__(self, parent, title): super(Frameclass, self).__init__(parent, title=title, size=(400, 200)) self.Centre() self.Show() self.regHotKey() self.Bind(wx.EVT_HOTKEY, self.handleHotKey, id=self.hotKeyId) self.regHotKey2() self.Bind(wx.EVT_HOTKEY, self.handleHotKey2, id=self.hotKeyId2) def regHotKey(self): """ This function registers the hotkey Alt+F12 with id=150 """ self.hotKeyId = 150 self.RegisterHotKey(self.hotKeyId,win32con.MOD_ALT, win32con.VK_F12)#the key to watch for def handleHotKey(self, evt): loop=True print('clicks on') while loop==True: #simulated left mouse click mouse.click() sleep(0.50) x=self.regHotKey2() print(x) if x==False: print('Did it work?') break else: pass ---------------------second keypress hotkey-------- def regHotKey2(self): self.hotKeyId2 = 100 self.RegisterHotKey(self.hotKeyId2,win32con.MOD_ALT, win32con.VK_F11) def handleHotKey2(self, evt): return False loop=False print(loop) if name=='main': showytitleapp=wx.App() #gotta have one of these in every wxpython program apparently Frameclass(None, title='Rapid Clicks') showytitleapp.MainLoop() #infinite manloop for catching all the program's stuff A: Your loop variable is locally scoped inside of handleHotKey. Because regHotKey2 is bound to handleHotKey2, which is a different listener, the event it generates will never affect the loop within handleHotKey. Besides that, the first line of handleHotKey2 is a return value, which will quit the function before the following two lines are executed. Out of curiousity, what output does x=self.regHotKey2(); print(x) produce? Try defining your loop variable at the class level instead of the function level - def __init__(self, parent, title): ... your original stuff ... self.clicker_loop = False and then modifying that loop in your handlers - def handleHotKey(self, evt): self.clicker_loop = True while self.clicker_loop: ... do the thing ... def handleHotKey2(self, evt): self.clicker_loop = False Please try this and tell me if this works. And maybe this will toggle the loop from the same hotkey... def handleHotKey(self, evt): if self.clicker_loop: self.clicker_loop = False else: self.clicker_loop = True A: I added these modules to my import: subprocess,signal,sys under my class I added these def init(self, parent, title): self.clicker_loop = False self.PID=1 def openClicker(self,event): self.PID=subprocess.Popen([sys.executable, "123.py"]) I had to import sys and add sys.executable to my popen otherwise i got an error everytime i tried to open another python program. def handleHotKey(self, evt): if self.clicker_loop: self.clicker_loop = False print(self.clicker_loop) self.PID.terminate() else: self.clicker_loop = True print(self.clicker_loop) self.openClicker(self) I kill the called loop process with self.PID.terminate(), otherwise it opens the seperate 123.py loop file. The seperate 123.py file contains this code: import mouse from time import sleep while True: mouse.click() sleep(1) What this basically does is call upon a separate python file with the subprocess module when the hotkey is pressed, then kills that process when the hotkey is pressed again. Thanks for the help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563396", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: access array content from a pointer returned from function I tried to write a program which used a function to read the data, store in an array and then tried to return the array to main() for the sorting process. Here's what I have #include <stdio.h> #include <stdlib.h> #define RESERVED_ARRAY_SIZE 100 int* read_data_from_files() { int* arr = (int*) malloc(sizeof(int) * 50); int arr_count; int status; int i,j ; arr_count =0; i=0; FILE *cfPtr; if ((cfPtr = fopen ("score.dat", "r"))== NULL) { printf("File cannot be opend\n"); } else { fscanf(cfPtr, "%d", &arr[i]); printf("%5d%5d\n", i, arr[i]); while (!feof (cfPtr)) { ++i; ++arr_count; status = fscanf(cfPtr, "%d", &arr[i]); if (status == EOF) { break; } else if (status != 1) { fprintf (stderr, "Error input\n"); getchar(); } if (arr_count >= RESERVED_ARRAY_SIZE) { fprintf(stderr, " The number of array is over.\n"); getchar(); } printf("%5d%5d\n", i, arr[i]); } fclose (cfPtr); } printf("arr_count=%d\n", arr_count); return arr; } int main() { int i; int arr_count; int* arr = (int*) malloc(sizeof(int) * 10); arr = read_data_from_files(); arr_count = sizeof(arr)/sizeof(arr[0]); printf("this check the size of array%d", arr_count); for (i=0; i<9; i++) { printf("%d ", i); printf("%d", *arr[i]); } selection_sort(arr, arr_count); getchar(); return 0; } My questions are 1. If functions cannot return 2 values, what shuold I do to pass the array size(the arr_count in my program) in the funcution to the main()? 2. If the function only returns the pointer of the array to the main(), can I figure out the size of the array in the main? what should I do ? Thans a lot for your assistants. A: No, you cannot figure out the size automatically. The standard way to return multiple values is to pass a pointer to a variable in which you want to store the extra return value: int* read_data_from_files(int *result_size) { ... *result_size = arr_count; ... return arr; } int main() { int arr_count; int *arr = read_data_from_files(&arr_count); ... } A: You could make a variable size in the main function, and have the function call pass the address to read_data_from_files() as an additonal argument. read_data_from_files() can then modify the value from inside the function, and you won't need to return it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563402", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dynamically adjust an iframe's height I have an iframe that contains some content from a site. I want the iframe to adjust to 100% of the src content's height. Bit of a noob at js - here's what I'm working with: <iframe id="frame" scrolling="no" frameborder="0" src="http://www.srcwebsite.org"></iframe> <script type="text/javascript"> function resizeIframe() { var height = document.documentElement.clientHeight; height -= document.getElementById('frame').offsetTop; height -= 20; /* whatever you set your body bottom margin/padding to be */ document.getElementById('frame').style.height = height +"px"; }; document.getElementById('frame').onload = resizeIframe; window.onresize = resizeIframe; </script> This works great to resize the height of the iframe to its page, but I want it to resize it to the height of the src... A: You can't access the height of the iframe's content because of Same Origin Policy (protocol, domain and ports must match). You could set up CORS, keep in mind it's not supported in IE until IE8.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563408", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Executing a bash script from a windows bat file Is there a way to call a bash script? (Or any linux like command) from a batch file (or VB script) on a windows box? Thanks K A: If you have Cygwin installed then a line like this in your batch file should run the bash script: bash scriptname.sh
{ "language": "en", "url": "https://stackoverflow.com/questions/7563411", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: IE7 CSS Grouping I have some classes that are grouped. However in IE7 and lower it doesn't implement any of the classes in the group. It just seems to ignore them: #subnav a, #subnav span { /* css here */ } And the html: <div id="subnav"> <ul class="depth-1"> <li class="selected"> <a href="someLink.html">Some Link</a> </li> <li> <a href="anotherLink.html">Another Link</a> </li> <li> <span>Header</span> <ul class="depth-2"> <li> <a href="google.com.au">Google</a> </li> </ul> </li> </ul> </div> Is CSS grouping not supported in IE7 and below or is something else causing this to happen? Thanks A: You could try a few things here: * *make sure this rule group is last in the css stylesheet to ensure that no other styles are overwriting these ones *make the selectors as specific as possible, to ensure the elements are targeted. So, instead of #subnav a, try div#subnav ul.depth-1 li.selected a *make sure the styles can be applied to those particular elements. a and span are inline elements and do not accept all styles.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563412", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using LDAP authentication with liquibase Is it possible to use LDAP authentication with Liquibase? If not, how have others solved the problem of automating changes to production database schemas using Liquibase (yet still keeping the database credentials secure)? A: LDAP is used for server-side authentication. Not all databases support it, for example MySQL only supports it in it's Enterprise version. Securing the credentials, used by clients like liquibase, falls into two categories: * *Protecting data in transit *Protecting credentials at rest To protect credentials in transit, I'd recommend using a JDBC driver which supports SSL. Some JDBC drivers support this feature, for example MySQL. Another approach is to tunnel the JDBC traffic over a SSH tunnel. Protecting credentials at rest (in configuration files) is more difficult and depends on how you plan to invoke liquibase. If you're using ANT, I'd suggest using the answer to this question on how to read encrypted property files.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563413", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Random code generator for coupon system Is this good enough for a random coupon code generator? Should I check and see if a code has already been used when I make a new code? What are the odds that this will repeat? $coupon_code = substr(base_convert(sha1(uniqid(mt_rand())), 16, 36), 0, 7); EDIT - here's my actual code: $coupon_code = substr(base_convert(sha1(uniqid(mt_rand())), 16, 36), 0, 7); $numrows = mysql_num_rows(mysql_query("SELECT id FROM generatedcoupons WHERE coupon_code='$coupon_code' LIMIT 1")); if($numrows>0){ $coupon_code = substr(base_convert(sha1(uniqid(rand())), 16, 36), 0, 7); $numrows = mysql_num_rows(mysql_query("SELECT id FROM generatedcoupons WHERE coupon_code='$coupon_code' LIMIT 1")); if($numrows>0) //error, show link to retry } A: Here's a coupon system that not only guarantees unique codes, but is very efficient when it comes to looking them up: // assuming MySQL table with (id, code, effect) mysql_query( "insert into `coupons` set `effect`='".$effect."'"); // "effect" will be some keyword to identify what the coupon does $id = mysql_insert_id(); $code = $id."F"; $codelen = 32; // change as needed for( $i=strlen($code); $i<$codelen; $i++) { $code .= dechex(rand(0,15)); } mysql_query( "update `coupons` set `code`='".$code."' where `id`=".$id); // now, when you are given a code to redeem, say $_POST['code'] list($code,$effect) = mysql_fetch_row( mysql_query( "select `code`, `effect` from `coupons` where `id`='".((int) $_POST['code'])."'")); if( $code != $_POST['code']) die("Code not valid"); else { // do something based on $effect } As you can see, it takes the ID from AUTO_INCREMENT, appends an F, then pads with random hexadecimal characters. You can make $codelen as high as you want, but 32 should be plenty (giving around 16**26 combinations even after the millionth coupon). A: Seems fairly random to me... I'd still probably double check that a code has not already been used when you create one on the very slight off chance that you do get a repetitive number. And most likely the chances of a repetition are slightly more than 1 in 36^8 or roughly 1:2,821,109,907,456. Note that since SHA1 gives back 40 digits in a hexadecimal string if you want there to be less chance that it will be duplicated you can always just increase your substr from (0,7) up to (0,29) (you can go even a little higher, but I doubt you want THAT big of a number) But I defs agree you should have some sort of unique coupon id stored in some database for making sure that you don't have duplicates, and it would be a great way to see how many coupons you guys created (and potentially how many got used? =D)
{ "language": "en", "url": "https://stackoverflow.com/questions/7563416", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Range.to_a example in "Programming Ruby" thanks for checking this question out. This is my first question here so any help/criticism appreciated. I'm working my way (beginner) through the free online version of Programming Ruby: The Pragmatic Programmer's Guide, version 1. The following example does not do (when I do it) what the book says it should: class VU include Comparable attr :volume def initialize(volume) # 0..9 @volume = volume end def inspect '#' * @volume end # Support for ranges def <=>(other) self.volume <=> other.volume end def succ raise(IndexError, "Volume too big") if @volume >= 9 VU.new(@volume.succ) end end Should do the following, according to the book, in irb: medium = VU.new(4)..VU.new(7) medium.to_a » [####, #####, ######, #######] medium.include?(VU.new(3)) » false But what does happen for me is medium.to_a returns with an array of the VU objects like so: #<VU:0x9648918> #<VU:0x96488b4> #<VU:0x964888c> #<VU:0x9648878> And that makes sense to me (I think). What doesn't make sense to me is the book's assertion that what should be returned is an array of '#'s. Wouldn't we need to invoke the inspect method in order to get those "#'s? Thanks! Ian A: Is that what you see in irb? inspect is called implicitly on return values in irb. You are correct in that array is filled with VU objects, but what should be displayed is the output of inspect for those objects. > x = VU.new(5) => ##### > x.class => VU > x.succ => ######
{ "language": "en", "url": "https://stackoverflow.com/questions/7563417", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Clear explanation of the "theta join" in relational algebra? I'm looking for a clear, basic explanation of the concept of theta join in relational algebra and perhaps an example (using SQL perhaps) to illustrate its usage. If I understand it correctly, the theta join is a natural join with a condition added in. So, whereas the natural join enforces equality between attributes of the same name (and removes the duplicate?), the theta join does the same thing but adds in a condition. Do I have this right? Any clear explanation, in simple terms (for a non-mathmetician) would be greatly appreciated. Also (sorry to just throw this in at the end, but its sort of related), could someone explain the importance or idea of cartesian product? I think I'm missing something with regard to the basic concept, because to me it just seems like a restating of a basic fact, i.e that a set of 13 X a set of 4 = 52... A: You're not quite right - a theta join is a join which may include a condition other than = - in SQL, typically < or >= etc. See TechNet As for cartesian product (or CROSS JOIN), it is an operation rather than an idea or concept. It's important because sometimes you need to use it! It is a basic fact that set of 13 x set of 4 = 52, and cartesian product is based on this fact. A: In my opinion, to make it simple, if you understand equijoin, you suppose should understand theta join. If you change the symbol = (equal) in equijoin to >=, then you already done theta join. However, I think it is quite difficult to see the practicality of using theta join as compared to equijoin since the join cause that we normally use is V.primarykey = C.foreignkey. And if you want to change to theta join, then it may depends on the value, as such you are doing selection. For natural Join, it is just similar to equijoin, the difference is just that get rid of the redundant attributes. easy!:) Hope this explanation helps. A: Leaving SQL aside for a moment... A relational operator takes one or more relations as parameters and results in a relation. Because a relation has no attributes with duplicate names by definition, relational operations theta join and natural join will both "remove the duplicate attributes." [A big problem with posting examples in SQL to explain relation operations, as you requested, is that the result of a SQL query is not a relation because, among other sins, it can have duplicate rows and/or columns.] The relational Cartesian product operation (results in a relation) differs from set Cartesian product (results in a set of pairs). The word 'Cartesian' isn't particularly helpful here. In fact, Codd called his primitive operator 'product'. The truly relational language Tutorial D lacks a product operator and product is not a primitive operator in the relational algebra proposed by co-author of Tutorial D, Hugh Darwen**. This is because the natural join of two relations with no attribute names in common results in the same relation as the product of the same two relations i.e. natural join is more general and therefore more useful. Consider these examples (Tutorial D): WITH RELATION { TUPLE { Y 1 } , TUPLE { Y 2 } , TUPLE { Y 3 } } AS R1 , RELATION { TUPLE { X 1 } , TUPLE { X 2 } } AS R2 : R1 JOIN R2 returns the product of the relations i.e. degree of two (i.e. two attributes, X and Y) and cardinality of 6 (2 x 3 = 6 tuples). However, WITH RELATION { TUPLE { Y 1 } , TUPLE { Y 2 } , TUPLE { Y 3 } } AS R1 , RELATION { TUPLE { Y 1 } , TUPLE { Y 2 } } AS R2 : R1 JOIN R2 returns the natural join of the relations i.e. degree of one (i.e. the set union of the attributes yielding one attribute Y) and cardinality of 2 (i.e. duplicate tuples removed). I hope the above examples explain why your statement "that a set of 13 X a set of 4 = 52" is not strictly correct. Similarly, Tutorial D does not include a theta join operator. This is essentially because other operators (e.g. natural join and restriction) make it both unnecessary and not terribly useful. In contrast, Codd's primitive operators included product and restriction which can be used to perform a theta join. SQL has an explicit product operator named CROSS JOIN which forces the result to be the product even if it entails violating 1NF by creating duplicate columns (attributes). Consider the SQL equivalent to the latter Tutoral D exmaple above: WITH R1 AS (SELECT * FROM (VALUES (1), (2), (3)) AS T (Y)), R2 AS (SELECT * FROM (VALUES (1), (2)) AS T (Y)) SELECT * FROM R1 CROSS JOIN R2; This returns a table expression with two columns (rather than one attribute) both called Y (!!) and 6 rows i.e. this SELECT c1 AS Y, c2 AS Y FROM (VALUES (1, 1), (2, 1), (3, 1), (1, 2), (2, 2), (3, 2) ) AS T (c1, c2); ** That is, although there is only one relational model (i.e. Codd's), there can be more than one relational algebra (i.e. Codd's is but one). A: All joins can be thought of as beginning with a cross product and then weeding out certain rows. A natural join weeds out all rows in which columns of the same name in the two tables being joine have different values. An equijoin weeds out all rows in which the specified columns have different values. And a theta-join weeds out all rows in which the specified columns do not stand in the specified relationship (<, >, or whatever; in principle it could be is_prefix_of as a relationship beween strings). Update: Note that outer joins cannot be understood this way, because they synthesize information (that is, nulls) out of nothing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563420", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Multiclass element selection clarification Assuming several multiclass divs as demonstrated in the following HTML: <div class="class_one class_two class_three classfour classfive classsix"> <div class="class_one class_two class_three classfour classfive"> <div class="class_one class_two class_three classfour classsix"> Is there a single Jsoup select expression that will select all 3 of them? To clarify, thinking that the "lowest common denominator" will select all 3, I tried the following: div[class=class_one class_two class_three classfour] But it selected none! On the other hand, using the full multiselect syntax works, but it can only select one of the above, e.g.: div[class=class_one class_two class_three classfour classfive classsix] Is there a way to select all 3 of them, using a single Jsoup select statement? A: This is not specific to Jsoup, but to CSS. The [attribute=name] selector does an exact match. Even the ordering matters. You want to use the .classname selector here instead. The following should work: Elements divs = document.select("div.class_one.class_two.class_three.classfour"); // ... Note that ordering of the classnames doesn't matter here. This selector selects all <div> elements which has all of the given classnames present. See also: * *Jsoup selector syntax *Jsoup Selector API javadoc
{ "language": "en", "url": "https://stackoverflow.com/questions/7563421", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Documenting JSON-RPC endpoints We have an extensive Java API that's exposed as JSON-RPC endpoints on our server. The problem is that the API documentation currently has to be duplicated in Javadoc and JSON-RPC API. Does anybody know of a tool or a framework that can automate the process of extracting Javadoc to be used for a JSON-RPC API documentation? Our JSON-RPC framework is very much homegrown. What I am looking for is anything that will let me parse the javadocs so that I can include the Javadoc snippets in my API docs in a meaningful way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563424", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Flyweight Examples in Java I am trying to create a flyweight object in Java. I've worked with a similar concept in Objective-C (Singleton Classes in Objective-C // I believe they are the same thing). I am trying to find a tutorial or an example or explanation online to learn how to create a flyweight object and use it, but I've searched on Google and I can't find anything descent. I went through 10 pages and they basically all plagiarize from one website which just explains the concept. I understand the concept - I need something to help me/teach me how to implement it in Java. Anyone has any suggestions/tutorials? Thanks! A: The Wikipedia entry for the flyweight pattern has a concrete Java example. EDIT to try and help the OP understand the pattern: As noted in my comment below, The point of the flyweight pattern is that you're sharing a single instance of something rather than creating new, identical objects. Using the Wiki example, the CoffeeFlavorFactory will only create a single instance of any given CoffeeFlavor (this is done the first time a Flavor is requested). Subsequent requests for the same flavor return a reference to the original, single instance. public static void main(String[] args) { flavorFactory = new CoffeeFlavorFactory(); CoffeeFlavor a = flavorFactory.getCoffeeFlavor("espresso"); CoffeeFlavor b = flavorFactory.getCoffeeFlavor("espresso"); CoffeeFlavor c = flavorFactory.getCoffeeFlavor("espresso"); // This is comparing the reference value, not the contents of the objects if (a == b && b == c) System.out.println("I have three references to the same object!"); } A: To follow up on the Wikipedia example that Brian cited... Usually, if you want to cache some objects (such as CoffeeFlavors) and have them shared between a number of flyweights (the CoffeeOrders), then you would make them statically available. But this is not at all necessary. The important part is that the CoffeeOrders are being given the shared objects when they're constructed. If the Orders are always only created by one singleton, like a "CoffeeOrderFactory," then the factory can keep a non-static cache of Flavors. However you accomplish it, your goal is to get all the Orders in the whole system to use the same exact set of Flavor objects. But at the end of the day, if you want to avoid creating many instances of CoffeeFlavor, then it usually needs to be created statically, just to make sure there's only one cache. Get it? A: I got this case. I think my solution was flyweight. INPUT * *A: C E *B: D C *C: E *A: B It asked me to create a tree and sort its children by name. Something like this: * *A: B C E *B: C D *C: E It's an easy task actually. But please notice that the first 'A' and the second 'A' in the input must refer to same object. Hence I coded something like this public Node add(String key){ Node node = nodes.get(key); if (null == node){ node = new Node(key); nodes.put(key, node); } return node; } This is the simplified version of the actual problem, but you should have the idea now. A: I also found this example, which has good Java code example. A: The "java.lang.Character" uses the flyweight pattern to cache all US-ASCII characters : see in class java.lang.Character$CharacterCache used by the Character.valueOf() method
{ "language": "en", "url": "https://stackoverflow.com/questions/7563435", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Which Layout supports android:layout_gravity? I came through many examples in internet.I found that neither Relative Layout nor Linear Layout supports android:layout_gravity.By it I mean the views inside these layouts does not support android:layout_gravity attribute. So any one having idea which layout supports android:layout_gravity and how to use it in better way? A: Children (that is, direct descendants in the View hierarchy) of LinearLayout do use layout_gravity (see LinearLayout.LayoutParams), but only on the "secondary" axis. So, in a vertical LinearLayout, center_horiztonal will work, but center_vertical will do nothing. Children of FrameLayout also support layout_gravity (see FrameLayout.LayoutParams). Keep in mind that the layout_* parameters set values in a LayoutParams object provided by the view parent. So a layout_* parameter will only have an effect if the parent view supports the parameter. A: Actually if you use RelativeLayout you don't need to use layout_gravity.Better way to position your layout's elements are android. Here you can get a good explanation how to use RelativeLayout.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563438", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Recursive function for building array from tree I have an array that looks like this: Array ( [0] => Array ( [term_id] => 23 [name] => testasdf [depth] => 1 ) [1] => Array ( [term_id] => 26 [name] => asdf [depth] => 2 ) [2] => Array ( [term_id] => 31 [name] => Another level deep [depth] => 3 ) [3] => Array ( [term_id] => 32 [name] => Another level deep [depth] => 2 ) [4] => Array ( [term_id] => 24 [name] => testasdf [depth] => 1 ) [5] => Array ( [term_id] => 27 [name] => asdf [depth] => 1 ) ) Here is the recursive function that I'm using, it works except in some cases (where the depth is greater it seems. function process(&$arr, &$prev_sub = null, $cur_depth = 1) { $cur_sub = array(); while($line = current($arr)){ if($line['depth'] < $cur_depth){ return $cur_sub; }elseif($line['depth'] > $cur_depth){ $prev_sub = $this->process($arr, $cur_sub, $cur_depth + 1 ); }else{ $cur_sub[$line['term_id']] = array('term_id' => $line['term_id'], 'name' => $line['name']); $prev_sub =& $cur_sub[$line['term_id']]; next($arr); } } return $cur_sub; } This is how the results look: Array ( [23] => Array ( [26] => Array ( [31] => Array ( [term_id] => 31 [name] => Another level deep ) ) [32] => Array ( [term_id] => 32 [name] => Another level deep ) ) [24] => Array ( [term_id] => 24 [name] => testasdf ) [27] => Array ( [term_id] => 27 [name] => asdf ) ) Any idea how I can have it so the term_id and name is shown for all depths? A: try this: function process(&$arr, &$prev_sub = null, $cur_depth = 1) { $cur_sub = array(); while($line = current($arr)){ if($line['depth'] < $cur_depth){ return $cur_sub; } if($line['depth'] > $cur_depth){ $prev_sub = $this->process($arr, $cur_sub, $cur_depth + 1 ); } $cur_sub[$line['term_id']] = array('term_id' => $line['term_id'], 'name' => $line['name']); $prev_sub =& $cur_sub[$line['term_id']]; next($arr); } return $cur_sub; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7563439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android:Is this possible to generate the view's Bitmap I have 4 layouts(views) and I wanna get their shortcuts. I use "getDrawingCache()",yeah,I get the pictures,but I found if I wanna get the pictures,I had to make them shown.(I mean they have to be displayed to the user). So Is there any way to get their pictures without displaying them?? Thanks in advance! A: This might work Window window = getLocalActivityManager().startActivity(Id,intent.addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP)); window.getDecorView().buildDrawingCache(); window.getDecorView().getDrawingCache(); This is what is done to update activities in tab activity. Im not sure but its worth a try.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563440", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to select rows with sum of group in sqlite3? Let say I have data in sqlite3 like this: |saleID|data| |1|a| |1|b| |1|c| |2|x| |2|y| |3|t| |4|x| |4|y| I want to count how many times saleID in table appear. How the sql syntax in sqlite to get result like this? |saleID|count| |1|3| |2|2| |3|1| |4|2| Thanks for coder.. A: select saleID, count(1) as [count] from sales group by saleID A: you just need to use group by: select saleID,COUNT(data) from Table group by salesID Regards A: SELECT saleID, COUNT(*) FROM YourTable GROUP BY saleID
{ "language": "en", "url": "https://stackoverflow.com/questions/7563442", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Adding magento to an existing website I was curious if anyone knows if it is possible to add magento to an existing website. I want the website look the same. The website has products and buttons/links for adding to shopping cart, but it has no shopping cart functionality. Is this possible? If so, where could I read up on this? Any help is greatly appreciated. thanks in advance. A: You could add some magento functionality by including the Mage.php file in your normal non-magento website. This would allow you to perform magento operations (such as add to cart, ...) Example: <?php include("location/to/app/Mage.php"); Mage::app(); // Any magento code is possible here :) ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7563443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Returning the last row from a mysql subquery when paginating a result set I'm using the following mysql query to create a pagination array -- for a list of documents -- in the form "Ab-Cf | Cg-Le | Li-Ru " etc... The subquery 'Subquery' selects the entire list of documents, and is variable depending on the user privileges, requirements etc -- so I'm trying to avoid altering that part of the query (and have used a simplified version here). I'm then selecting the first and last row of each page range -- i.e, the 1st and 10th row, the 11th and 20th row etc., determined by $num_rows_per_page. SELECT * FROM ( SELECT @row := @row + 1 AS `rownum`, `sort_field` FROM ( SELECT @row := 0 ) r, ( SELECT D.`id`, D.`display_name` as display_field, D.`sort_name` as sort_field FROM Document D ORDER BY `sort_field` ASC ) Subquery ) Sorted WHERE rownum % $num_rows_per_page = 1 OR rownum % $num_rows_per_page = 0 This is working just fine, and gives me a result set like: +---------+-----------------------------------+ | rownum | index_field | +---------+-----------------------------------+ | 1 | Alternaria humicola | | 10 | Anoplophora chinensis | | 11 | Atherigona soccata | | 20 | Carlavirus RCVMV | | 21 | Cephus pygmaeus | | 30 | Colletotrichum truncatum | | 31 | Fusarium oxysporium f. sp. ciceri | | 40 | Homalodisca vitripennis | | 41 | Hordevirus BSMV | | 50 | Mayetiola hordei | | 51 | Meromyza saltatrix | | 60 | Phyllophaga | | 61 | Pyrenophora teres | +--------+------------------------------------+ However -- I can't for the life of me work out how to include the last row of the subquery in the result set. I.e., the row with rownum 67 (or whatever) that does not meet the criteria of the WHERE clause. I was hoping to somehow pull the maximum value of rownum and add it to the WHERE clause, but I'm having no joy. Any ideas? Happy to try to rephrase if this isn't clear! Edit -- here's a more appropriate version of the subquery: SELECT * FROM ( SELECT @row := @row + 1 AS `rownum`, `sort_field` FROM ( SELECT @row := 0 ) r, ( SELECT D.`id`, D.`display_name` as display_field, D.`sort_name` as sort_field FROM Document D INNER JOIN ( SELECT DS.* FROM Document_Status DS INNER JOIN ( SELECT `document_id`, max(`datetime`) as `MaxDateTime` FROM Document_Status GROUP BY `document_id` ) GS ON DS.`document_id` = GS.`document_id` AND DS.`datetime` = GS.`MaxDateTime` AND DS.`status` = 'approved' INNER JOIN ( SELECT `id` FROM Document WHERE `template_id`= 2 ) GD ON DS.`document_id` = GD.`id` ) AG ON D.id = AG.document_id ORDER BY `sort_field` ASC ) Subquery ) Sorted WHERE rownum % $num_rows_per_page = 1 OR rownum % $num_rows_per_page = 0 But, a key point to remember is that the subquery will change depending on the context. A: Please try adding OR rownum=@row to your WHERE clause (in my testing case this works)
{ "language": "en", "url": "https://stackoverflow.com/questions/7563444", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to rotate label of a bar chart and add offset in core plot? just wondering if there is a way to rotate the labels placed on bar charts and add offset to it ? Thank you. Below my delegate implementation. Note the padding on label -(CPTLayer *)dataLabelForPlot:(CPTPlot *)plot recordIndex:(NSUInteger)index { CPTMutableTextStyle *whiteTextStyle = [[[CPTMutableTextStyle alloc] init] autorelease]; whiteTextStyle.color = [CPTColor whiteColor]; whiteTextStyle.fontSize = 14.0f; CPTTextLayer *label = [[CPTTextLayer alloc] initWithText:@"Test" style:whiteTextStyle]; label.paddingLeft = -100.0f; // <--- return [label autorelease]; } A: Use the labelOffset and labelRotation properties on the plot. These are inherited from CPTPlot by all Core Plot plots. You should not set the padding in -dataLabelForPlot:recordIndex:.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563446", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rails server hangs when a User method I created is called. No errors and I don't know how to test it I call this method (with helper method detailed below as well), defined in User.rb model def get_random_items return nil unless groups_as_member if groups_as_member == 1 assignments = groups_as_member.assignments.limit(5) random_items = Post.rand_by_post(assignments) end random_groups = groups_as_member.sort_by{rand}.slice(0,5) random_items = Array.new i=0 return unless random_groups until i == 10 do random_groups.each do |group| assignments = group.assignments.limit(5) if y = Post.rand_by_post(assignments) random_items << y i+=1 if random_items == 5 return random_items end else return random_items end end end return random_items end helper method rand_by_post in Post.rb def self.rand_by_post(assignments) find_by_id(assignments.rand.post_id) end in the user controller show action: def show @public_groups = Group.public @groups_member = @user.groups_as_member @groups_as_owner = @user.groups_as_owner @random_items = @user.get_random_items end when I comment out the call in the user show action, the user show works fine on my development and production server. But when I try to user the method the servers will just hang there, not doing anything. I can't find any errors in the server logs or the heroku logs. My test writing skills are pretty limited, and I am having trouble writing one for the entire method. Can anyone spot a problem? A: if your random_groups is empty, your helper method get_random_items will go into an endless loop until i == 10 do ... end. That could be the reason. You might want to change return unless random_groups to return if random_groups.empty?
{ "language": "en", "url": "https://stackoverflow.com/questions/7563451", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Comparing images by color Possible Duplicate: How to reduce color palette with PIL I'm trying to create a program that can identify similar images based off common colors. I've been experimenting with histograms and some of the filters in PIL but I feel like I'm reinventing the wheel. So: How can I reduce an image to X number of colors?
{ "language": "en", "url": "https://stackoverflow.com/questions/7563454", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Mod_Rewrite with multiple PHP variables and dynamic text So here's the deal: episode.php?s=1&e=3 brings up information for season 1 episode 3. So make it SEO friendly I want to be able to have users be able go to the following: domain.com/episodes/ShowName_Season_1_Episode_3_The_Title_Of_The_Episode.html (or without the .html, doesn't really matter). This is what I have so far: RewriteRule ^episodes/([a-z0-9-]+)_$_([a-z0-9-]+)_$_([a-z0-9-]+).html episode.php?s=$1&e=$2 I know this is not right...how can I make it take the two numbers in the rewritten URL and associate them with PHP GET variables in the actual URL? I know how to do more basic mod_rewrites but this one has been confusing me. I am guessing it is something stupid, so thanks in advance for your patience. A: Here's what you can do: RewriteEngine ON #domain.com/episodes/ShowName_Season_1_Episode_3_The_Title_Of_The_Episode.html RewriteRule ^episodes/([a-z0-9\-]+)_Season_([0-9]+)_Episode_([0-9]+)_(.*)$ episode.php?s=$2&e=$3 [NC,L] #Even more SEO friendly: http://domain.com/ShowName/Season/3/episode/4/title/ RewriteRule ^episodes/([a-z0-9\-]+)/season/([0-9]+)/episode/([0-9]+)/(.*)/? episode.php?s=$2&e=$3 [NC,L] #or Even more SEO friendly: http://domain.com/episodes/ShowName/season-3/episode-1/title RewriteRule ^episodes/([a-z0-9\-]+)/season\-([0-9]+)/episode\-([0-9]+)/(.*)/? episode.php?s=$2&e=$3 [NC,L] I don't recommend to use "_" for SEO but "-"
{ "language": "en", "url": "https://stackoverflow.com/questions/7563457", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to easily include links to other pages of my site within my PHP files? I was wondering if there is a way to make the following process more automated (so links automatically update throughout if the links get changed). I have a PHP site, with a front controller. Now I'm wondering how would I go about displaying certain links (to pages) within the different PHP files? (I don't want to actually do so manually...as that would mean if the page name got changed I'd have to manually flick through all the files). Basically what I'm looking for is a way I can include links to pages on my site easily and automatically. I had an idea of storing them in an config array and then using some sort of wrapper/helper function in the PHP files to retrieve them from the config array and display them (but not sure if its the best way forward or if there are other ways)? Perhaps something like how WordPress does it (although I'm not familiar with it I've heard that its using a similar technique...) as what I have is a front controller alongside a mapping array (containing the urls of the pages) - if that helps. Appreciate all approaches and responses. A: I recommend looking at some of PHP's great MVC frameworks for the best examples of using the strengths of MVC to do dynamic routing and access those routes in your views, so they update automatically. Code Igniter, CakePHP, Zend Framework I'm partial to CodeIgniter myself, but they all have their strengths. I seriously suggest you look into adopting one of these frameworks if your application is complex enough to need this level of route management. No need to reinvent the wheel. Using a framework lets you spend less time messing with the nuts and bolts and more time just building your application. Whether you use the framework or not, they are probably better examples of good object oriented design than you are likely to find in wordpress.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563458", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I statically reject different instantiations of an existential type? First attempt It's difficult to make this question pithy, but to provide a minimal example, suppose I have this type: {-# LANGUAGE GADTs #-} data Val where Val :: Eq a => a -> Val This type lets me happily construct the following heterogeneous-looking list: l = [Val 5, Val True, Val "Hello!"] But, alas, when I write down an Eq instance, things go wrong: instance Eq Val where (Val x) == (Val y) = x == y -- type error Ah, so we Could not deduce (a1 ~ a). Quite right; there's nothing in the definition that says x and y must be the same type. In fact, the whole point was to allow the possibility that they differ. Second attempt Let's bring Data.Typeable into the mix, and only try comparing the two if they happen to be the same type: data Val2 where Val2 :: (Eq a, Typeable a) => a -> Val2 instance Eq Val2 where (Val2 x) == (Val2 y) = fromMaybe False $ (==) x <$> cast y This is pretty nice. If x and y are the same type, it uses the underlying Eq instance. If they differ, it just returns False. However, this check is delayed until runtime, allowing nonsense = Val2 True == Val2 "Hello" to typecheck without complaint. Question I realize I'm flirting with dependent types here, but is it possible for the Haskell type system to statically reject something like the above nonsense, while allowing something like sensible = Val2 True == Val2 False to hand back False at runtime? The more I work with this problem, the more it seems I need to adopt some of the techniques of HList to implement the operations I need as type-level functions. However, I am relatively new to using existentials and GADTs, and I am curious to know whether there's a solution to be found just with these. So, if the answer is no, I'd very much appreciate a discussion of exactly where this problem hits the limit of those features, as well as a nudge toward appropriate techniques, HList or otherwise. A: So you want a constructor that allows you to use heterogeneous types, but you want comparisons between heterogeneous types that are knowable at compile time to be rejected. As in: Val True == Val "bar" --> type error allSame [] = True allSame (x:xs) = all (== x) xs allSame [Val True, Val "bar"] --> False But surely: (x == y) = allSame [x,y] So I'm pretty sure a function with satisfies these constraints would violate some desirable property of a type system. Doesn't it look like that to you? I am strongly guessing "no, you can't do that". A: In order to make type-checking decisions based on the contained types, we need to "remember" the contained type by exposing it as a type parameter. data Val a where Val :: Eq a => a -> Val a Now Val Int and Val Bool are different types, so we can easily enforce that only same-type comparisons are allowed. instance Eq (Val a) where (Val x) == (Val y) = x == y However, since Val Int and Val Bool are different types, we cannot mix them together in a list without an additional layer which "forgets" the contained type again. data AnyVal where AnyVal :: Val a -> AnyVal -- For convenience val :: Eq a => a -> AnyVal val = AnyVal . Val Now, we can write [val 5, val True, val "Hello!"] :: [AnyVal] It should hopefully be clear by now that you cannot meet both requirements with a single data type, as doing so would require both "forgetting" and "remembering" the contained type at the same time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563459", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: how to limit the characters in access to more than 255 How to limit the characters in access to more than 255? for example, I want it the memo or text box to limit it to max 300 characters. In Access 2010 A: If you want to limit a memo field in a table to no more than 300 characters, open the table in design view and add this as the field's Validation Rule property. Len([memo_field])<301 Substitute your field's name for memo_field. You can also add a Validation Text property to display a more user-friendly message when the rule is violated. With no Validation Text, that rule would produce this message ... which might not be very clear to a user: *One or more values are prohibited by the validation rule 'Len([memo_field])<301' set for 'YourTableName.memo_field'. Enter a value that the expression for this field can accept.* You also mentioned a text box. If it is a text box bound to a memo field, you can validate the character length in the text box's Before Update event. If the text box is named txtMemo_field: Private Sub txtMemo_field_BeforeUpdate(Cancel As Integer) If Len(Me.txtMemo_field) > 300 Then MsgBox "Please limit data to maximum of 300 characters." Cancel = True End If End Sub After the message box, the cursor will be still located within the text box, and the user will not be allowed to move to another form field without supplying an acceptable value for txtMemo_field. A: Just to address a point in @HansUp's answer: Is Null Or Len([memo_field])<301 ... If you don't want to allow Nulls, drop the "Is Null Or" part. There is no need to explicitly test for nulls in a constraint. A constraint doesn't have to evaluate TRUE for it to be satisfied. If the Access database engine (ACE, Jet, whatever) actually had a spec it would read like this: A table constraint is satisfied if and only if the specified search condition is not false for any row of a table. According to three-valued logic required to handle nulls, the search condition LEN(NULL) < 301 evaluates to UNKNOWN and the table constraint would be satisfied (because UNKNOWN is not FALSE). However, Access has no such spec, so we must test and see that the above assertions are indeed true (simply copy and paste into any VBA module, no references required, creates a mew blank mdb in the user's temp folder, then creates table, Validation Rule -- without the explicit test for null -- then attempts to add a null with success, Q.E.D.): Sub WhyTestIsNull() On Error Resume Next Kill Environ$("temp") & "\DropMe.mdb" On Error GoTo 0 Dim cat Set cat = CreateObject("ADOX.Catalog") With cat .Create _ "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=" & _ Environ$("temp") & "\DropMe.mdb" With .ActiveConnection Dim Sql As String Sql = _ "CREATE TABLE Test (" & _ " ID INTEGER NOT NULL UNIQUE, " & _ " memo_field MEMO" & _ ");" .Execute Sql End With ' Create Validation Rules Dim jeng Set jeng = CreateObject("JRO.JetEngine") jeng.RefreshCache .ActiveConnection .Tables("Test").Columns("memo_field") _ .Properties("Jet OLEDB:Column Validation Rule").Value = _ "LEN(memo_field) BETWEEN 1 AND 300" jeng.RefreshCache .ActiveConnection Sql = "INSERT INTO Test (ID, memo_field) VALUES (1, NULL);" .ActiveConnection.Execute Sql Sql = "SELECT * FROM Test;" Dim rs Set rs = .ActiveConnection.Execute(Sql) MsgBox rs.GetString(2, , , , "<NULL>") Set .ActiveConnection = Nothing End With End Sub A: Change its Data type to Memo. max field size of text field Regards
{ "language": "en", "url": "https://stackoverflow.com/questions/7563461", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Why aren't my push and pop methods working? I'm trying to implement a stack in Perl where I have an array. I want to push items on the array, pop items out and print out the new array like so: "1,2,3,5,6 How can I do that? My code just adds the number 6 to the top of the array. #!usr/bin/perl @array = 1..5; push @array, 6; #Push the number 6 into the array pop @array, 4; #Pop the number 4 out of the array print "The array is now $array[-1].\n"; A: First things first, use use strict; use warnings;. What's pop @array, 4; supposed to do? Pop four elements? splice(@array, -4); Replace the last element with the value 4? $array[-1] = 4; Filter out the value 4? @array = grep { $_ != 4 } @array; Reference: * *pop *splice *grep By the way, #usr/bin/perl is meaningless. It should be #!/usr/bin/perl. By the way, the escape sequence for a newline is \n, not /n. A: The whole point of a stack is you can only access items from the top. You can only push an item onto the top of stack or pop an item off the top of the stack. The elements in the middle are not accessible. Using Perl's shift and unshift functions you can also implement queues and dequeues (or double-ended queues.) #!/usr/bin/perl use strict; use warnings; my @array = 1..5; push @array, 6; push @array, 7; my $top = pop @array; print "Top was $top\n"; print "Remainder of array is ", join(", ", @array), "\n"; A: Incorrect syntax: pop @array, 4; pop should take at most, one argument (the array). It will pop the last element from the array stack, whereas shift takes the first element from the stack.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563474", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Save the contents of a PDF file as spoken audio using AppleScript I have built a simple script which takes a string and converts it to an audio file: say "This is only a test." using "Fred" saving to file (((path to desktop) as string) & "audio.aiff" I'd like to edit the script so that instead of using the string "This is only a test" it would fetch a PDF document and use the text in the document to create an audio file. A: Skim, a free PDF viewer, might be of interest to you. It's scriptable and features an AppleScript command to extract the text from certain PDF pages. Once you've downloaded Skim, you can run this script: tell application "Skim" open (POSIX file "/path/to/PDF/document.pdf") set the stuff to (get text for page 1 of document 1) as string --change 'page 1' to whatever page number you need --if you want all the pages, just use 'every page' end tell say the stuff using "Fred" saving to file (((path to desktop) as string) & "audio.aiff") Happy coding! :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7563477", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Facebook PHP SDK - Have to reauthenticate during new browser session? Hopefully this should be quick and easy. session_start(); include("facebook.php"); $facebook = new Facebook(array( 'appId'=>'xxxxx50274xxxxx', 'secret'=>'xxxxxb932d62fbc6287feb18e5exxxxx', 'cookie'=>true )); $fbuser = $facebook->getUser(); if (empty($fbuser)){ $fbloginurl=$facebook->getLoginURL(); echo "<html><body><a href='$fbloginurl'>Click</a></body></html> } else { die("Authenticated"); } In this example, the first time I click the link to give permissions to the app to access my FB account, everything works fine. I can keep refreshing the page, and I get the "Authenticated" confirmation. However, every time I restart the browser (starting a new session), it doesn't authenticate the app automatically and I have to click the link again. Of course as soon as I click the link I am immediately redirected back to the source page and presented with the "Authenticated" confirmation. Is there any way of not having to click the authentication link during new browser sessions and have it authenticate automatically? I need to do this without a PHP Header directive, as I want the first time the user gives permissions to the app to be triggered by a manual click. My FB login is persistent ("stay logged in" option is checked). Thanks a lot for any help. A: If I am understanding your scenario correctly (this is not an iframe app, correct?), this is all down to losing the website session cookie when the browser is closed. Once that cookie is gone, there is nothing to identify the user to your server-side code and so no way to know if the user has previously authorized your app. You need to find a way to persistently identify the user, or at least identify that he has already given permissions. The simplest way would probably be to set your own (permanent) cookie once the user has first authenticated. Then whenever the session cookie is lost, check the presence of the permanent cookie and if it's there, do a PHP redirect to Facebook (which will be invisible to the user). If there is no cookie, present the HTML link to the user like you are doing now. A: Comparing it to my code, the only difference I see is that I check to see if $fbuser is valid - if it isn't send me to the login screen. I'm also using top.location.href. // Login or logout url will be needed depending on current user state. if ($fbuser) { $logoutUrl = $facebook->getLogoutUrl(); } else { $loginUrl = $facebook->getLoginUrl(array('scope' => 'publish_actions', 'canvas' => 1, 'fbconnect' => 0, 'redirect_uri'=>config_item('facebook_url').$pf)); echo "<html><body><script> top.location.href='" . $loginUrl . "'</script></body></html>"; exit(0); } Hope that helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563478", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP is slow when printing large amount of text I made an ajax application, which worked great on my local dev server, but when I moved it online, one particular request got really slow. This request is quite complicated - it loads a lot of stuff from database and creates quite big text output, around 120kB. Since the app was written in a short time, there was a lot of space for optimization. Naturally I was trying to find what's slowing my app most - and I was surprised - it was the last final echo which was printing all calculated information. I used Firebug to measure the times. The request took ~100ms without printing the info, just calculating, but ~400ms with printing... so the simple echo command took around 300ms! Then I tried PHP's microtime() to get more precise results... but suddenly there was no significant difference between printing and not printing. So I guess the problem is somewhere else - in the area of sending text to Apache and then to the client... I don't understand this stuff, but I read somewhere that this might be caused by small Apache buffer. Can I do something about it? I don't think that 120kB is too much - just few years ago, in the time of table layouts, most of the big websites had html source of this size. Could this be a problem of the webhosting? I could try to contact them but naturally it would be easier if I could solve this myself. A: The answer is really simple. My download speed is around 300kB/s so downloading a 120kB page can't be faster than ~300ms. That's all and I'm really stupid :D A: ob_start(); echo $huge_string; ob_end_flush();
{ "language": "en", "url": "https://stackoverflow.com/questions/7563479", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery ajax data by form fields I am processing a form with jQuery ajax. I have the following jQuery code: $.ajax({ url: 'formprocess.php', type: 'post', data: $('#myForm input[type=\'text\']'), dataType: 'json', success: function(json) { alert('pass'); } }); And my form is: <form id="myForm"> <input type="text" name="parent[47]child[230][26]" value="1" /> <input type="text" name="parent[47]child[230][27]" value="2" /> <input type="text" name="parent[28]child[231][29]" value="3" /> <input type="text" name="parent[28]child[231][31]" value="4" /> </form> And it works fine for form posts over ajax. On the php side it shows up as: $_POST : array = parent: array = 47: array = child: array = 230: array = 26: string = "1" 27: string = "2" 28: array = child: array = 231: array = 29: string = "3" 31: string = "4" But I'd like to split it on the javascript side so that it loops and passes each parent separately. So in this case it would post back twice: $_POST : array = parent_id = 47 child: array = 230: array = 26: string = "1" 27: string = "2" AND $_POST : array = parent_id = 28 child: array = 231: array = 29: string = "3" 31: string = "4" So I think I need to use: $('#myForm input[type=\'text\']').each(function(i, tbox) { tboxname = tbox.attr('name'); var myregexp = /parent\[(\d+)\]child\[(\d+)\]\[(\d+)\]/; var match = myregexp.exec(tboxname); var parent_id = match[1]; var child = 'child['+match[2]+']['+match[3]+']'; } But now I have 2 string values and have lost my object and value. A: You're correct - using .each() in this case is the right approach, but it'll just let you iterate over each input element, and won't really know anything about the "array" inside the name attribute for each one. That seems to be your primary issue here; javascript is just seeing the value of your name parameter as a string, and not an array of values. I wouldn't think of this as a multi-dimensional array in the eyes of js... the each() will just see one big list of elements that you need to invent your own logic to parse through. Here's what I would try... var parsedData = {}; $('#myForm input[type=\'text\']').each(function(i){ var thisInput = $(this); var thisName = $(this).attr('name'); // parse your string here, by using conditional statements or maybe by using eval() // ... This is where "your own logic" mentioned above would go =) parsedData.["someValue"+i] = thisInput.val(); }); ...And from here you would use the parsedData var to pass into your $.ajax call. Hope this helps
{ "language": "en", "url": "https://stackoverflow.com/questions/7563480", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Client-side browser language/plugin that supports sockets? I am a Application Developer (java,c,c#) and do not have experience with any web-based languages yet. I want to embed an application in a webpage. The application may need to connect to a database that could be on the same host as the webpage. But most importantly, I need client-side socket support (like java's Socket class). I could relatively easily implement it using a java applet, but it seems java applets are not used very often anymore, and the java runtime is required on the clients pc. Javascript seems like the most widely used, but is it capable of directly using the clients network? Silverlight seems to be gaining popularity and might fit my needs, but has the same problem as java applets (not guaranteed to be installed on the client machine). What are the other alternatives? Thanks for your help! A: Java is still alive, and I think in your case Java works better than JavaScript. I wouldn't worry so much about people having the Java runtime.. it takes a few minutes to get it and it's still very common. The main reason here is that you already know Java well and don't have experience with web-based languages- why spend loads of time with something else? Java applets are a bit dated though. So the new HTML5 provides socket support(thanks Pointy), and that's the wisest choice overall(use JavaScript + HTML5 ). A: After some research I think my two best options are Silverlight or a Java Applet. Both have rich client-side capability and can be easily embedded in a web-page. Not everyone is guaranteed to have either installed but both are relatively easy to install and run on almost any desktop. No linux for silverlight though :( This may be possible with pure HTML5/javascript as well, but would require significantly more work because you would not get the pre-made libraries of C# or Java. Java Applets are quite dated however, and it would take a sizable amount of work to get a java applet looking like a modernly styled web app. For that reason I decided to try out silverlight. Thanks for all the tips! Edit: After some further digging it seems like silverlight will not work for me since it has many restrictions on the use of client side sockets. http://msdn.microsoft.com/en-us/library/cc645032%28v=vs.95%29.aspx A java applet would be much more flexible.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563482", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Stupid idea: Mac speech from PHP server? I want to synthesize Mac OS X speech, but I'm using a PC. Can I set up a PHP server on my Macbook at home, and have it synthesize text for me, and return it to me through a web request? Like http://mymacbook.com/speak.php?t=why+hello+there What secret PHP codes will unlock this possibility? I know I can synthesize speech on the command line with say -o "output.aiff" -f "input.txt" but I need help with the connective tissue here. And no - I do not want links to Cepstral or AT&T's online speech synthesizer, because I want to use special Mac speech synthesis syntax. A: <?php file_put_contents('input.txt', $_GET['t']); exec('say -o output.aiff -f input.txt'); header("Content-Type: audio/x-aiff"); readfile("output.aiff"); unlink("output.aiff"); exit;
{ "language": "en", "url": "https://stackoverflow.com/questions/7563483", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How transferable is JavaFX 1.3 knowledge to JavaFX 2.0? I'm embarking on a project to develop a desktop application but my expertise have been in the web application development realm. I was about to refresh my knowledge on Swing programming when I learned on JavaFX which seems to be a much better alternative. At least version 2.0 seems to fit that bill. My dilemma is that there are no books out on the topic. I was wondering if reading up on 1.3 first would be of help? Or is the syntax too, architecture, etc too different? I understand that there was something called JavaFX Script which is now gone in lieu of a Java API which is a bit why I'm wondering if reading up on 1.3 might be a futile effort? Does anyone have any recommendations on learning resources other that JavaFX api, sample applications and such? A: Obviously the syntax has changed, but if you already know Java, coding with JavaFX 2.0 will look familiar. The one take away from existing books, is that most of the framework, controls, shapes, and effects, etc., from JavaFX 1.3 was ported over to JavaFX 2.0. So the basic knowledge of the framework can be gleaned from one of the older books. That would help you in at least knowing what component to use and then allow you to research it further to see how it now works in JavaFX 2.0. There is also a lot of helpful documents at javafx.com. New books will be out within the next six months or so and may be available on-line sooner than that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563488", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: query the html taken from PHP's file_get_contents using jQuery If I have $html = file_get_contents('http://www.some-url.com/index.php'); how do I query the html using jQuery? A: You will need to output the HTML onto the page then use jQuery to query it once the page is loaded.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563492", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Routing error from jQuery UI tabs with ajax I'm using Rails and jQuery UI to implement tabs in each user's profile. I've got it working without ajax - with ajax, things go south. I'm new to Rails and jQuery and am hoping someone can help me identify what's going wrong. * *<div id="tabs-1"> is the first tab and it is associated with ProfilesController by default. That works by using an <a href>. *<div id="tabs-2"> would access MessagesController and load a partial show_messages that loads @user.messages. What happens instead is that when I click "Messages" I get an ActionController::Routing error in Profiles#show. No route matches {:action=>"show", :controller=>"messages", :id=>[#<Message id: 3, user_id: 2,...>, #<Message id: 4, user_id: 2,...">]} My code is below: application.js: $(function() { $( "#tabs" ).tabs({ ajaxOptions: { error: function( xhr, status, index, anchor ) { $( anchor.hash ).html( "Couldn't load this tab. We'll try to fix this as soon as possible. " + "If this wouldn't be a demo." ); } } }); }); My profile show.html.erb: <div id="tabs"> <ul id="infoContainer"> <li><a href="#tabs-1"></a></li> <li><%= link_to "Messages", message_path(@user.messages) %></a></li> <ul> <div id="tabs-1"> </div> </div> My _show_messages partial in MessagesController: <div id="tabs-2"> <% for 'message' in @user.messages %> <div class="message"> </div> <% end %> </div> A: in show.html.erb message_path(@users.messages) is wrong. Try messages_path which should point to the index action of the messages controllr. Here I am assuming you are using the standard Rails convection for messages routes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563495", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Open a remote file using paramiko in python slow I am using paramiko to open a remote sftp file in python. With the file object returned by paramiko, I am reading the file line by line and processing the information. This seems really slow compared to using the python in-built method 'open' from the os. Following is the code I am using to get the file object. Using paramiko (slower by 2 times) - client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(myHost,myPort,myUser,myPassword) sftp = client.open_sftp() fileObject = sftp.file(fullFilePath,'rb') Using os - import os fileObject = open(fullFilePath,'rb') Am I missing anything? Is there a way to make the paramiko fileobject read method as fast as the one using the os fileobject? Thanks!! A: Your problem is likely to be caused by the file being a remote object. You've opened it on the server and are requesting one line at a time - because it's not local, each request takes much longer than if the file was sitting on your hard drive. The best alternative is probably to copy the file down to a local location first, using Paramiko's SFTP get. Once you've done that, you can open the file from the local location using os.open. A: I was having the same issue and I could not afford to copy the file locally because of security reasons, I solved it by using a combination of prefetching and bytesIO: def fetch_file_as_bytesIO(sftp, path): """ Using the sftp client it retrieves the file on the given path by using pre fetching. :param sftp: the sftp client :param path: path of the file to retrieve :return: bytesIO with the file content """ with sftp.file(path, mode='rb') as file: file_size = file.stat().st_size file.prefetch(file_size) file.set_pipelined() return io.BytesIO(file.read(file_size)) A: Here is a way that works using scraping the command line (cat) in paramiko, and reading all lines at once. Works well for me: import paramiko client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.WarningPolicy()) client.connect(hostname=host, port=port, username=user, key_filename=ssh_file) stdin, stdout, stderr = client.exec_command('cat /proc/net/dev') net_dump = stdout.readlines() #your entire file is now in net_dump .. do as you wish with it below ... client.close() The files I open are quite small so it all depends on your file size. Worth a try :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7563496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Rails 3 does not show jQuery Date Picker I followed a Railscast by RyanB to add jQuery date_picker to a form and and got stuck for a couple days now. According to the instruction, there are only three changes: * *Change application.html.erb to include jQuery and jQuery-ui (see my application.html.erb below) *Change date_select field to text to accommodate jQuery. I made the change in my _form.html.erb: <%= f.text_field :born_in %> *Add to application.js the following statement: $(function() { $("#spec_born_in").datepicker(); }); The tricky problem for me is that I am using FullCalendar (a JavaScript plugin). For some reason, if I add anything to applicaiton.js, FullCalendar won't show up. Therefore, I need to put the function definition to a file I called application_jquery_helper.js, and load it after loading FullCalendar's js files. I have done all these but in my form, the text field is just a text field, and jQuery datepicker would not show up. I wonder what I did incorrectly that prevented jQuery datepicker from showing up. The only reason I can think of is the order in which I included js files in my application.html.erb, but I don't know how to fix it. Below is my rather big in application.html.erb: <head> <%= csrf_meta_tag %> <%= render 'layouts/stylesheets'%> <%= javascript_include_tag :defaults %> <!-- <%=stylesheet_link_tag'blueprint/screen',:media=>'screen'%> <%=stylesheet_link_tag'blueprint/print',:media=>'print'%> --> <%= stylesheet_link_tag 'formtastic', 'formtastic_changes', :cache => "base" %> <%= stylesheet_link_tag "http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/redmond/jquery-ui.css", "application" %> <%= javascript_include_tag "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js", "http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js", "application" %> <%= stylesheet_link_tag "fullcalendar.css" %> <%= stylesheet_link_tag "application.css" %> <%= javascript_include_tag "jquery.js" %> <%= javascript_include_tag "jquery.rest.js" %> <%= javascript_include_tag "rails.js" %> <%= javascript_include_tag "application.js" %> <!-- these are needed for the calendar. --> <%= javascript_include_tag "jquery-ui-1.8.11.custom.min.js" %> <%= javascript_include_tag "fullcalendar.js" %> <%= javascript_include_tag "calendar.js" %> <%= javascript_include_tag "application_jquery_helper.js" %> Comments or suggestions are very much appreciated! A: I believe you are trying to access an element when the DOM isn't fully loaded. To correct this issue: $(document).ready(function(ev) { $("#spec_born_in").datepicker(); }); You can also look at jQuery's .live() functionality if you need "future" support.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563497", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WCF DateTime to NSDate I am using a web services which returns a JSON WCF DateTime. The string goes like \/Date(1316397792913+0800)\/ I am interested in extracting out the 1316397792 which is the time since 1st Jan 1970 in seconds. So that I can use the NSDate timeIntervalSince1970 method to get the present time. I cropped out the last 3 digits as it's in milliseconds and the timeIntervalSince1970 takes in seconds. Here's what I am currently doing which does not work for dates somewhere before 2001 which has a time interval in ms since 1970 less than 10 characters. NSString *dateString = @"\/Date(1316397792913+0800)\/"; NSLog(@"dateString :%@", dateString); NSDate *date = [NSDate dateWithTimeIntervalSince1970: [[dateString substringWithRange:NSMakeRange(6, 10)] intValue]]; NSLog(@"NSDate:%@", date); dateString :/Date(1316397792913+0800)/ NSDate:2011-09-19 02:03:12 +0000 Therefore, I need a better work around playing with the dateString which does not assume everytime we will be feteching 10 characters. A: You can simply get the substring between the index of ( and the index of +. Something like: NSRange begin = [dateString rangeOfString:"("]; NSRange end = [dateString rangeOfString:"+"]; NSString* milliSecondsSince1970 = [dateString substringWithRange:NSMakeRange(begin.location + 1, end.location - begin.location - 1)]; P.S: Check for the one off error.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563498", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: First Android App I'm fairly new to the whole android scene, and I decided to start off with something simple, a Celsius to Fahrenheit converter. Here's the block of code I'm using to do the actual math (x-32)*5/9 where x=input for Celsius Temp. convertbutton.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { double result = new Double(input.getText().toString())-32*5/9; output.setText(Double.toString(result)); I know that x-32*5/9 is not a valid way to do the (x-32)*5/9 formula, but I can't put the -32 in parenthesis. Just looking for ways to get it to subtract 32 from the input first, and then for it to multiply that by 5/9. Any help would be much obliged. A: You may have been confused by the parentheses in this expression: new Double(input.getText().toString())-32*5/9 It would work if you parenthesized the whole thing up to 32: (new Double(input.getText().toString())-32)*5/9 ^ here and here ^ But it’s easier to read if you put the value in a temporary variable: double input_value = new Double(input.getText().toString()); double result = (input_value - 32) * 5/9; A: You are probably looking for Double.parseDouble(String); Here is an example... String s = "56.7"; double input = Double.parseDouble(s); input = (input - 32d) * (5d/9d); Edit: the d is necessary to force java to interpret the constants as doubles
{ "language": "en", "url": "https://stackoverflow.com/questions/7563499", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Given a string denoting a type, I need to know if it's a value or reference type I'm writing a T4 template and got stuck on this. If consumers of the template write: Please generate stuff for: string myString I need to generate if (myString != null) { DoStuffWith(myString) } Whereas if they write Please generate stuff for: int myInt I need to generate simply DoStuffWith(myInt) And this needs to work with custom value/reference types too. If I forced the template consumers to write System.String myString or System.Int32 myInt, I imagine this could be done without trouble; there's presumably some GetTypeFromFullTypeName method hiding in the framework somewhere. But I don't want to make them do that. Any ideas on how my T4 template could get at this information, so I could conditionally generate the right code? A: * *Get the corresponding instance of the Type class (i.e. Type.GetType or Assembly.GetType). *Check the IsValueType property. The number of types with "short names" is very limited, they're actually C# keywords. So you can use a case statement, e.g. case "string": return typeof (string); You'll also need some rules for ?, and for finding a specific concrete version of generic classes (recursion will be helpful). Don't try to translate int? into System.Nullable``1[System.Int32], instead use typeof(System.Nullable<>).MakeGenericType(FindType("int")). A: You could emit the null check always, even for value types. This is not a compiler error, but produces a warning which you could suppress: #pragma warning disable CS0472 if (myInt != null) { DoStuffWith(myInt) } #pragma warning restore CS0472
{ "language": "en", "url": "https://stackoverflow.com/questions/7563500", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why do some java classes seem to return a value when constructed? E.g. import java.util.*; public class mainXX { public static void main(String args[]){ System.out.println(new Date()); } } If I run this code I'm creating a new Date object but not calling any methods, it only calls the default constructor, which looks like this: public Date() { this(System.currentTimeMillis()); } How does the System.out.println end up printing a string date (Tue Sep 27 12:04:42 EST 2011) from this declaration as a constructor can't return a value? I know this is a simple question but I can't figure out what is happening. Thanks, m A: When calling println on an Object the Object's toString() method will automatically called. Thus, the new Date is constructed based on the current system time, then the Date.toString() method is called, returning a String. The String is then printed to the console. A: You are correct that constructors themselves do not return values, but the expression formed by applying the new operator to a constructor "call", does produce a value. In other words new is an operator. The expression new C ( args ) invokes the constructor C on the given arguments. The result of the new expression is the newly constructed object. It is the new operator, not the constructor, that is producing the value. (I'm being technical and saying "producing" instead of "returning" because I think that is in the spirit of your question.) ADDENDUM By way of further explanation: Constructors, do not actually "return" objects the way methods do. For example: public class Point { private double x; private double y; public Point (double x, double y) { this.x = x; this.y = y; } public double getX() {return x;} public double getY() {return y;} @Override public String toString() { return "(" + x + "," + y + ")"; } } The methods getX, getY, and toString return values, so when used in an expression like this p.getX() a value is returned. The constructor has no return statement. More importantly you don't call it directly. That is you cannot say System.out.println(Point(1, 2)); That would be an error. Instead, you use a "new-expression" which has the form new applied to the constructor name applied to an argument list. This invokes the constructor and produces a new object. For example: Point p = new Point(4, 3); The right hand side is a newly created point object. All I was pointing out is that nothing is returned from the constructor itself; you have to apply the new operator to get the point object. Because the new expression produces an object, we can apply methods directly to it. The following are all acceptable: new Point(4, 3) // produces a point object new Point(4, 3).getX() // produces 4 new Point(4, 3).getY() // produces 3 new Point(4, 3).toString() // produces "(4,3)" As other answerers have pointed out, in Java when you use an object in a context where a string is expected, the toString() method is automatically called. So System.out.println(new Point(4, 3)) would actually print (4,3). A: The toString() method, available on all Java objects, is called whenever a string representation of an object is needed. A: Tom G is not quite correct. System.out is a PrintStream. PrintStream.println is overloaded so that the value produced (the date Object) is printed differently to other types. As per the Java API, this: * *calls print(Object), which *calls String.valueOf(Object) (not toString as suggested), which *calls toString() if the object isn't null The result of that last toString (valueOf) is a String, which is then printed by PrintStream as indicated by the documentation. A: The method System.out.println(); targets the value of an object in java, let it be string or integer or any other custom defined object. So when you try to invoke this method on any object the toString() method associated with that object is automatically called, resulting in that value. Hope this clears your doubt.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563502", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I selecting multiple columns, only one of which is distinct? (ORACLE SQL) I want to be able to do this: INSERT INTO TABLE_1(<LIST OF COLUMNS>) SELECT <LIST OF ROWS> FROM (SELECT DISTINCT <OTHER COLUMNS> FROM TABLE_2); How can I do this? I receive an error when I try to do it now. Note that <LIST OF COLUMNS> is the same in both cases I use it, and also not that the fields in <OTHER ROWS> could, but do not necessarily exist in <LIST_OF COLUMNS>. A: OK, a little philosophical treatise here... "Distinct" means "reject duplicates". And to detect duplicated rows you have compare them for equality first. If you just compare rows on all columns, everything is fine: two rows are either equal or they are not, there is no third possibility. So you always know whether a row should be rejected as a duplicate or not. However, if you try to compare rows by comparing a subset of their columns, you run into trouble: rows that are equal when compared on the subset of their columns may not be equal when compared on all columns. So are they duplicates or not? * *If you consider them duplicates and reject one of the rows, you'll also be rejecting values that may not exist in the other row. You are effectively losing data (not to mention that which data you loose is random, so even the data you keep is essentially useless). *If you don't consider them duplicates, then you are not really making them distinct on the column subset, contradicting what you were trying to do in the first place. So making rows distinct on the subset of columns can only be done: * *if you don't keep the the other columns, *or by "merging" values in other columns by subjecting them to aggregate functions such as MAX, COUNT, SUM etc.. This is the reason why GROUP BY must cover all non-aggregated columns. A DISTINCT is really just a GROUP BY on all columns.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563509", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Animate both width and height on click with jQuery Trying to animate both the width and the height of these boxes on click. See fiddle: http://jsfiddle.net/CqDXn/1/ I've been successful with getting the width to animate... no just need to prevent that awkward jump at the end of the animation. edit: worth noting I cannot set a static height on the li's A: * *What's 200? in em? px? use a measurement. '200px'. *You didn't animate the height as well as the width: {width: '200px', height: '200px'} *I dropped the .active css rule for auto height. The animation needs to take care of that. code: $(document).delegate('.rewards-process li:not(.active)', 'click', function(e) { var toActive = $(this); $('.rewards-process li.active').addClass('transition'); $('.rewards-process li.active').animate({ width:'90px' , height: '90px'},1000,function() { $('.rewards-process li.active').removeClass('active').removeClass('transition'); }); $(toActive).animate({ width:'200px' , height: '200px'},300,function(){ //animation complete $(toActive).addClass('active') }); }); I sometimes use this hack for figuring out a dynamic height: function getElementHeight(e, width) { $("body").append("<div id='test' style='width:" + width + "'>" + e.html() + "</div>").hide(); var h = e.outerHeight(); e.remove(); return h; } You need to make sure the CSS doesn't mess this up. Basically you create the element with the final width, calculate its height and then remove it. This function will return a number, you'll need to add px and you can use it in your animation. But you don't really need this. Height animates automatically for you, your CSS rules just disabled it. For example, this fiddle will work just fine. A: To animate the height, just add a height value under the width in the animate call. That jump at the end is caused by the browser trying to automatically re-layout all the elements. In order to prevent that, you should put them all into a grid, then re-layout the grid each time the animation finishes. A: This line on your css is causing the jump. .rewards-process .active img, .rewards-process .active p {display:block; } Try removing the "display:block" property and it should went smoothly. Find a way to have a remedy for that element. It should be easy.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use QSortFilterProxyModel to filter a tree model that only display children nodes with their parents? I have a working tree model derived from QAbstractItemModel and I wish to filter it using a QSortFilterProxyModel subclass to display only children nodes of certain criteria. For example I have the following tree: A - B -- C1 -- C1 -- C1 --- C2 - D - E I want to filter this tree with the condition that the node has name == C1 and display only the nodes with C1 and their children like this: C1 C1 C1 - C2 I already have a subclass with filterAcceptsRow() re-implemented that can partially do what I want but it will still show the parent and grandparent of C1 nodes: A - B -- C1 -- C1 -- C1 --- C2 I think this is because for children nodes to even be considered, their parent has to pass the filterAcceptsRow() test, am I right? How can I implement filterAcceptRows() or other methods such that it can do what I have described? I have asked this question sometime back in qtcentre and qtforum but did not get any useful reply. I tried to move the indices of the QSortFilterProxyModel subclass directly using beginMoveRows and endMoveRows inside filterAcceptsRow() but that just crashes the test application due to dangerous const_cast. A: Okay, I've found a solution to my problem. Just use QTreeView::setRootIndex() with index B as the input argument. Index B becomes the root index of the QTreeView, which is hidden and only its children are shown in full. I felt really dumb after finding this solution. Guess I was too focused on using the proxy model to modify how the data is presented, I had totally forgotten about QTreeView. A: I dont think this is possible to achive using QSortFilterProxyModel. The reason for that is that this class only filters elements - menas it hides (or not) some elements, basing on given criteria. What you want to do is restructuring tree into new one (having choosen elements from arbitary position at root-children). This is only possible by creating your own QProxyModel descendant and implementing yourself tree-rebuilding, and mapping indexes between old and new tree. Describing exactly how to do this is a bit long for an answer here. A: Of course setRootIndex is the solution for this case, but if you will be looking for more complicated model manipulations you may consider using custom proxy models like http://lynxline.com/category/models/
{ "language": "en", "url": "https://stackoverflow.com/questions/7563512", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Android: How can I achieve/draw an arrow and put a text on top of it using Canvas/Paint? I want to achieve the below picture (i made it via excel). Here are the requirements: * *arrow down shape *"GOAL" text on top of it *tip of the arrow should be pointed on the given x,y *transparent effect (i think its setAlpha(0..255)) *gradient effect (top to bottom) *emboss effect (optional) *lighting effect (optional) Any guidance is appreciated. *i don't have idea on how to draw. please guide us via code snippets example. UPDATES I just need small icon. A: you have to go for nine patch image. set backgrond of textview is "nineparch image". and setyour text view at x,y using absolute layout. Nine patch is available here: http://developer.android.com/guide/developing/tools/draw9patch.html it may help you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563513", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a compact way of telling the C# compiler to use the base Equals and == operator? I am fairly new to C#, and I come from a C++ background. I have defined a struct, and the (Microsoft) compiler keeps popping up the error CA1815 "'GenericSendRequest' should override Equals" I read a bit around and saw that C# structs derive from ValueType which impleents a generic Equals using reflection. This confused me more: * *Why does the compiler create an error instead of a warning if its just a performance issue? *Why does it define that generic Equals in the first place if it's not going to let you use it? So how can I tell the compiler that "I don't care"? Something similar with just declaring assignment operator in a C++ class without providing definition to acknowledge that I know what I am doing. So far my solution has been to include: public static bool operator ==(GenericSendRequest lhs, GenericSendRequest rhs) { return lhs.Equals(rhs); } public static bool operator !=(GenericSendRequest lhs, GenericSendRequest rhs) { return !lhs.Equals(rhs); } public override bool Equals(object obj) { return base.Equals(obj); } //Yes, it also makes me override GetHashCode since I'm overriding Equals. public override int GetHashCode() { return base.GetHashCode(); } in my struct, which is just awful. Edit: This is the struct definition: public struct GenericSendRequest { public LiveUser Sender; public LiveUser[] Receivers; public Message Msg; public ServiceHttpRequest HttpRequest; } Its usage is just multiple return values from a function: public static GenericSendRequest CreateGenericSendRequest(...); A: This is definitely not an error, its only a warning - and that warning even only will show up if you have enabled code analysis as part of your build. It's a suggestion for performance optimization - take it that way. Edit: Turns out this is configurable: Go to Project Properties | Code Analysis | Run this rule set.. Open Expand the Performance section - for CA 1815 you can select whether you want this to be a warning, an error or none. A: You got a little lost in the IDE somehow, this is not a compiler error. It is a code analysis error, performed by a tool known as FxCop. You can disable it with Analyze + Configure, untick the "Enable Code Analysis on Build" option. The tool is a little naggy, its use is more as a reminder that you might have done something unwise. Which in this case is pretty unlikely, this is not the kind of struct you can meaningfully compare without doing a lot of work. It is a performance warning, the default equality comparer for a struct uses reflection and that's not very efficient. But you'll make it a lot less efficient by implementing a correct version of Equals(). There is something else wrong, a struct in C# does not at all behave like a struct in C++. It should only be used for simple values that can be easily copied, given that it is a value type. You should make this a class instead. Solves the analysis error too.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563519", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Android - referencing string array using another string to avoid using SQLite I've searched for this but I'm not exactly sure what I should be searching for. I'm trying to avoid using a SQLite DB and was wondering is it possible to call a string using the value of another string. Eg. If I have in a xml file this: <string-array name="bob"> <item>1</item> <item>4</item> <item>7</item> <item>11</item> </string-array> And in a Java file this: String name = "bob"; can I then do something like this: String[] holder = getResources().getStringArray(R.array.name); Thanks! A: If I guess correctly what you are needing is getIdentifier(). Take into account that this method is expensive and it is much more efficient to retrieve resources by identifier.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563520", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Playing sound using AVAssetReader I am using AVAssetReader to get the individual frames from a video file (see code below). I would like to know how I can play the audio from the video at the same time. I tried to separate the audio into a new file and play it using AVAudioPlayer, but that crashes if I am using it at the same time as the AVAssetReader. NSAutoreleasePool *pool = [NSAutoreleasePool new]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString* fullPath = [[documentsDirectory stringByAppendingPathComponent:@"sample_video.mp4"] retain]; NSString *urlAddress = fullPath; NSURL *url = [NSURL fileURLWithPath:urlAddress]; AVURLAsset *urlAsset = [[AVURLAsset alloc] initWithURL:url options:nil]; NSArray *tracks = [urlAsset tracksWithMediaType:AVMediaTypeVideo]; AVAssetTrack *track = [tracks objectAtIndex:0]; NSDictionary* trackDictionary = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:kCVPixelFormatType_32BGRA] forKey:(id)kCVPixelBufferPixelFormatTypeKey]; AVAssetReaderTrackOutput *asset_reader_output = [[AVAssetReaderTrackOutput alloc] initWithTrack:track outputSettings:trackDictionary]; AVAssetReader *asset_reader = [[AVAssetReader alloc] initWithAsset:urlAsset error:nil]; [asset_reader addOutput:asset_reader_output]; [asset_reader startReading]; while (asset_reader.status == AVAssetReaderStatusReading){ CMSampleBufferRef sampleBufferRef = [asset_reader_output copyNextSampleBuffer]; if (sampleBufferRef){ [self performSelectorOnMainThread:@selector(processFrame) withObject:nil waitUntilDone:YES]; } CMSampleBufferInvalidate(sampleBufferRef); CFRelease(sampleBufferRef); } [pool release];
{ "language": "en", "url": "https://stackoverflow.com/questions/7563522", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Using Memory Mapping or Unlocked Stream Operation? I am working on a FUSE implementation for FAT32 under Linux (I know this is already available in the Linux Kernel, but this is a school assignment). The FAT32 filesystem is created with the mkfs.msdos command, which I will later map into memory with posix_madvise, or use an unlocked stream by means of posix_fadvise. I am not sure what should I base my choice on, I mean, what the pros and cons of each method are (in terms of performance, memory usage, etc). I have seen a few examples out there which combine the use of madvise with mmap, but no information was provided as to whether fadvise should be used with mmap too, or, to start with, the difference between the fadvise/madvise and POSIX implementations posix_fadvise/posix_madvise. Any point in the right direction will be greatly appreciated. A: Unless you want to limit yourself to ~2.5 GB filesystems or requiring a 64-bit machine, your choices are to use mmap and dynamically manage what part of the filesystem you keep mapped, or use normal read/write operations. I would probably go for the latter. mmap is overrated as a performance optimization, and has drawbacks like filling up your virtual address space, so I would tend to only use mmap when you really need to treat a file as memory - for instance, storing process-shared synchronization objects, executable code, or large data you want to feed to an API that only accepts in-memory data (for example, qsort).
{ "language": "en", "url": "https://stackoverflow.com/questions/7563528", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Calculate entropy of probability distribution of two data sets- text analysis & sentiment in C# I'm using a 1.6M tweet corpus to train a naive bayes sentiment engine. I have two Dictionaries of n-grams (Dictionary<string,int> where the string is my n-gram and the int is the # of occurrences of the n-gram in my corpus). The first list is pulled from the positive tweets, the second list is pulled from the negative tweets. In an article on this subject, the authors discard common n-grams (i.e. n-grams that do not strongly indicate any sentiment nor indicate objectivity of a sentence. Such n-grams appear evenly in all datasets). I understand this quite well conceptually, but the formula they provide is rooted in mathematics, not code, and I'm not able to decipher what I'm supposed to be doing. I have spent the last few hours searching the web for how to do this. I've found examples of entropy calculation for search engines, which is usually calculating the entropy of a string, and the most common code block has been ShannonsEntropy. I'm also relatively new to this space, so I'm sure my ignorance is playing a bit of a part in this, but I'm hoping somebody on SO can help nudge me in the right direction. To summarize: Given two Dictionaries, PosDictionary & NegDictionary, how do I calculate the entropy of identical n-grams? Psuedo-code is fine, and I imagine it looks something like this: foreach(string myNGram in PosDictionary) { if(NegDictionary.ContainsKey(myNGram) { double result = CalculateEntropyOfNGram(myNGram); if(result > someThetaSuchAs0.80) { PosDictionary.Remove(myNGram); NegDictionary.Remove(myNGram); } } } I think that's the process I'll need to take. What I don't know is what the CalculateEntropyOfNGram function looks like... (Edit) Here is the link to the pdf used to describe the entropy/salience process (section 5.3) A: Equation (10) in the paper gives the definition. If you have problems reading the equation, it is a short notation for H(..) = -log(p(S1|g)) * p(S1|g) - log(p(S2|g)) * p(S2|g) - ....
{ "language": "en", "url": "https://stackoverflow.com/questions/7563537", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Object Debugger gives me Extraneous Property And Inferred Property error on opg I have everything right in my header. I followed the Dev Doc for adding my location and address to my header but I get these warnings. Can someone tell me what I am doing wrong? Extraneous Property Objects of this type do not allow properties named og:language. Extraneous Property Objects of this type do not allow properties named og:email. Extraneous Property Objects of this type do not allow properties named og:phone_number. Extraneous Property Objects of this type do not allow properties named og:fax_number. Extraneous Property Objects of this type do not allow properties named og:latitude. Extraneous Property Objects of this type do not allow properties named og:longitude. Extraneous Property Objects of this type do not allow properties named og:street-address. Extraneous Property Objects of this type do not allow properties named og:locality. Extraneous Property Objects of this type do not allow properties named og:region. Extraneous Property Objects of this type do not allow properties named og:postal-code. Extraneous Property Objects of this type do not allow properties named og:country-name. Inferred Property The og:locale property should be explicitly provided, even if a value can be inferred from other tags. A: now facebook require you to add og:locale to meta tag too they just require when they announce new open graph beta <meta property="og:locale" content="fr_FR" /> http://developers.facebook.com/docs/beta/opengraph/internationalization/ A: The link in your comment doesn't spit out any errors. Were you putting old Meta tags on your page? A: i have same problem try to read this http://developers.facebook.com/docs/beta/opengraph/internationalization/ use this <meta property="og:locale" content="en_us" /> <meta property="og:locale:alternate" content="ar_ar" /> <!-- optional -->
{ "language": "en", "url": "https://stackoverflow.com/questions/7563538", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: prevent ajax call from firing repeatedly $('.myDiv').click(function(event){ $.ajax({ url: '', dataType: 'json', success: function(json) { for (var i = 0; i < json.length; i++) { var response = json[i]; $('.result_new').append('<p>' + response.name + '</p>'); } //$('.content').append('<p>' + response.total + '</p>'); } }); }) event.stopPropagation() isn't preventing the ajax call from being called repeatedly. Is there a function for this in Jquery? A: $('.myDiv').click(function(){ if( !$(this).hasClass('loading') ) { //add control class $(this).addClass('loading'); //do ajax... $.ajax({ success: function() { $('.myDiv').removeClass('loading') } }) } }); A: event.stopPropagation() only prevents the event from bubbling up (from .myDiv to it's parent element until reaching the window). It doesn't prevent the function from executing. You can use various methods to identify whether the request was sent or not, for example set .data(), e.g: $(".myDiv").click(function() { if (typeof $(this).data('inTheMiddleOfAnAJAXCall') == "undefined") { $(this).data('inTheMiddleOfAnAJAXCall', true); // Create an AJAX Call } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7563540", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do i pass a generator yield statement to another function. -Python i've been reading on this site and can't seem to find the specific answer i want. i've tried reading david beasly's slides on iteration and generators but still can't quite get the answer i'm looking for though the question seems simple. i'm running a clock-based simulation (Brian for neural networking) and i have a generator that is manipulating the outputs and adding them to a running sum (in order for there to be n exponential decay for a simple low-pass filter). i then want to take the outputs of these generators, at each time-step and then use them in another function to update some of the state variables, it says that since the item is of the generator type i cannot do this. code and explanation of code is as follows: import numpy our_range=numpy.arange(0*ms,duration+defaultclock.dt,defaultclock.dt) a=our_range c=defaultclock.t #this is a clock that is part of the program i'm running, it updates every #timestep and runs through the range given above def sum_tau(neuron): #this gives a running sum which i want to access (the alphas can be ignored as they are problem specific) for c in a: #had to express it like this (with c and a) or it wouldn't run if c ==0: x=0 elif defaultclock.still_running()==False: return else: x = x*(1-alpha) + p(neuron)*alpha print x yield x #p(neuron) just takes some of the neurons variables and gives a number b=sum_tau(DN) #this is just to specify the neuron we're working on, problem specific @network_operation def x(): b.next() the @network_operation means that every clock timestep the function below will be executed, therefore updating the sum to it's required value. Now what i want to do here is update a value that is used for the simulation (where d is the output to another generator, not shown, but very similar to b) by typing: ron= (d/(1-b)) However, it says i cannot use a generator object in this way, i have used print statements to determine that that b (and d) give the outputs i want every timestep (when the simulation is run) but I cannot seem to take these outputs and do anything with them. (more specifically unsupported operand type '-' for int and generator. i tried converting it to a number with float() but obviously this doesn't work for the same reason, i feel there must be a very simple solution to my problem but i can't seem to find it. Thanks in advance. A: "more specifically unsupported operand type '-' for int and generator" Take the hint. You can't use a generator in a trivial formula. You have to "expand" it with a generator expression. ron= (d/(1-b)) Has a generator b, right? b is not a "value". It's some kind of sequence of values. So, you have to apply each value in the sequence to your formula. ron = [ d/(1-x) for x in b ] will get each value of the sequence and compute a new value. (It's not clear if this is actually useful, since the original ron= (d/(1-b)) when b is a collection of values doesn't make much sense.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7563541", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cannot access variable through JavaScript - scope error? I have some data in a separate .js file similar to this: data = new Object(); data['cat'] = ['Mr. Whiskers','Wobbles']; data['dog'] = ['Toothy']; data['fish'] = ['goldy','roose']; function getStuff(info) { var stuff = data[info.value]; return stuff; } Now in another html file with a block, I have something like this: function theDrop(dynamic) { alert(getStuff(dynamic)); } The box says undefined, why? A: What are you passing to theDrop? If you want to call the .value then you need to pass the whole object over otherwise you will get undefined Live Demo var select = document.getElementById("selectme"); select.onchange = function(){ theDrop(this); } data = new Object(); data['cat'] = ['Mr. Whiskers','Wobbles']; data['dog'] = ['Toothy']; data['fish'] = ['goldy','roose']; function getStuff(info) { var stuff = data[info.value]; return stuff; } function theDrop(dynamic) { alert(getStuff(dynamic)); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7563542", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }