text
stringlengths
8
267k
meta
dict
Q: Bookmark with date in the URL I use Google Analytics, and the first thing I want to check every day is the current day's statistics. But there's no way to bookmark the current day. The URL for any given day is: https://www.google.com/analytics/reporting/dashboard?id=XXXXXXX&pdr=20110921-20110921 You can see a date range at the end of the URL. 20110921 meaning 9-21, 2011. How can I write a little javascript bookmarklet for Firefox to change the URL to the current date depending on what day I click on it? A: JavaScript has date methods that can individually give the parts of a date, but .toISOString() might perhaps work for your application most concisely. Very little string manipulation would have to be performed on the result to get the UTC date in the correct format. For example: javascript: d = new Date().toISOString().slice(0, 10).replace(/-/g, ''); location = "https://www.google.com/analytics/reporting/dashboard?id=XXXXXXX&pdr=" + d + "-" + d; A: Try this - it uses a Date object to get the date: var date = new Date(); var str = ""; str += date.getFullYear(); str += pad2(date.getMonth() + 1); str += pad2(date.getDate()); function pad2(n) { var str = String(n); if(str.length < 2) str = "0" + str; return str; } location.href = "https://www.google.com/analytics/reporting/dashboard?id=XXXXXXX&pdr="+str+"-"+str; Bookmarklet: javascript:(function(){function d(a){a=String(a);a.length<2&&(a="0"+a);return a}var c=new Date,b="";b+=c.getFullYear();b+=d(c.getMonth()+1);b+=d(c.getDate());location.href="https://www.google.com/analytics/reporting/dashboard?id=XXXXXXX&pdr="+b+"-"+b})(); A: To build on the answer by @PleaseStand - Firefox even has a non-standard Date.toDateLocale() function. So the whole thing can be simplified even further: javascript:void(location.href = "https://www.google.com/analytics/reporting/dashboard?id=XXXXXXX&pdr=" + new Date().toLocaleFormat("%Y%m%d-%Y%m%d")) A: * *Customize this code below with your Google Analytics ID, timezone offset, and other desired parameters. *Use a site like this to convert JavaScript to a bookmarklet. *Rejoice. var gaID = YOUR_ID; var hourOffset = 8; var rowCount = 50; var utcDate = new Date(new Date().toUTCString()); utcDate.setHours(utcDate.getHours() - hourOffset); var localDate = new Date(utcDate); var todayDate = localDate.toISOString().split("T")[0].replace(/-/g, ""); location.href = "https://analytics.google.com/analytics/web/#/report/advertising-adwords-keywords/" + gaID +"/_u.date00=" + todayDate + "&_u.date01=" + todayDate + "&explorer-table.plotKeys=%5B%5D&explorer-table.rowCount=" + rowCount; A: I know this is a really old thread, but it is still relevant. I found that if you set up your report using todays date, then edit the URL and use a future date, it will default to the current date's statistics. For example, I use this: https://analytics.google.com/analytics/web/#/dashboard/xxxxxxxxxxxxxxxx/xxxxxxxxxxxxxxxx/_u.date00=20221130&_u.date01=20221130/ The date codes are both the same date 2 years in the future. This causes analytics to use show the current dates stats.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509010", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: UTF-8 characters display differently after import to mySQL I have a mySQL database full of accented characters. The DB is populated periodically from MS Access 2010. In Access you'll see é è à Ü. In the export process in Access UTF-8 encoding is specified. Open the resulting text file in UltraEdit on my PC and you'll see "Vieux Carré" and UE says the encoding is U8-DOS. The files are uploaded via FTP and imported via LOAD DATA LOCAL INFILE queries like this LOAD DATA LOCAL INFILE '$dir/$t.$ext' INTO TABLE `$t` FIELDS OPTIONALLY ENCLOSED BY '|' TERMINATED BY ';' LINES TERMINATED BY '\n' In mySQL the field collation is set to utf8_general_ci. If you query mySQL from the command line or from phpMyAdmin you'll see "Vieux Carré". What am I doing wrong? A: If you're using LOAD DATA INFILE with a file that has a charset that's different from your database's default, you need to specify what character set the file is in: LOAD DATA LOCAL INFILE '$dir/$t.$ext' INTO TABLE `$t` CHARACTER SET utf8 FIELDS OPTIONALLY ENCLOSED BY '|' TERMINATED BY ';' LINES TERMINATED BY '\n' Note that the database character set is database-wide, and is different than the table character set and the column character set. SHOW CREATE DATABASE database_name will show you the database charset.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509014", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hooking Python standard library modules Question I've written a replacement threading module for Python. What's the best method to go about hooking all uses of the usual threading module from the standard library with my own? The hooking should be opt-in, and on a per project, or per executable basis. When this statement is executed: import threading I want my module to be loaded instead of the default. Note that in future, I may also hook several of the other standard modules, so a solution that addresses hooking a few modules is best. Why I've implemented IO concurrency via greenlets and Linux's eventfd() and epoll() system calls. It works transparently except for a sys.modules hook and a replacement socket class. Looking to make this hooking nicer and more consistent. A: Can you not just put your replacement threading module in some directory, and make sure that directory is listed in PYTHONPATH when you want to use it? That should mean that directory is searched before the default places when importing threading, and Python will find your module and stop. A: You might try using python's meta_path hook: http://www.python.org/dev/peps/pep-0302/ It'll allow you add an object which can override part of the importing process. I think you'll be able to substitute your own modules for the standard modules with that way. I'm not sure its better then patching sys.modules though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509016", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Limitations on sending through UDP sockets I have a big 1GB file, which I am trying to send to another node. After the sender sends 200 packets (before sending the complete file) the code jumps out. Saying "Sendto no send space available". What can be the problem and how to take care of it. Apart from this, we need maximum throughput in this transfer. So what send buffer size we should use to be efficient? What is the maximum MTU which we can use to transfer the file without fragmentation? Thanks Ritu Thank you for the answers. Actually, our project specifies to use UDP and then some additional code to take care of lost packets. Now I am able to send the complete file, using blocking UDP sockets. I am running the whole setup on an emulab like environment, called deter. I have set link loss to 0 but still my some packets are getting lost. What could be the possible reason behind that? Even if I add delay (assuming receiver drops the packet when its buffer is full) after sending every packet..still this packet losts persists. A: It's possible to use UDP for high speed data transfer, but you have to make sure not to send() the data out faster than your network card can pump it onto the wire. In practice that means either using blocking I/O, or blocking on select() and only sending the next packet when select() indicates that the socket is ready-for-write. (ideally you'd also not send the data faster than the receiving machine can receive it, but that's less of an issue these days since modern CPU speeds are generally much faster than modern network I/O speeds) Once you have that logic working properly, the size of your send-buffer isn't terribly important. (i.e. your send buffer will never be large enough to hold a 1GB file anyway, so making sure your program doesn't overflow the send buffer is the key issue whether the send buffer is large or small) The size of the receive-buffer on the receiver is important though... best to make that as large as possible, so the receiving computer won't drop packets if the receiving process gets held off of the CPU by another program. Regarding MTU, if you want to avoid packet fragmentation (and assuming your packets are traveling over Ethernet), then you shouldn't place more than 1468 bytes into each UDP packet (or 1452 bytes if you're using IPv6). (Calculated by subtracting the size of the necessary IP and UDP headers from Ethernet's 1500-byte frame size) A: Also agree with @jonfen. No UDP for high speed file transfer. UDP incur less protocol overhead. However, at the maximum transfer rate, transmit errors are inevitable (such as packet loss). So one must incorporate TCP like error correction scheme. End result is lower than TCP performance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509020", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: iphone sdk Localizable.strings files displaying incorrecting in xcode 4.1 after upgrading After upgrading to iphone xcode 4.1 build 4B110F all of my localizable.strings files are showing up as gibberish in the xcode editor. I created these files using UTF-16. I can not find a way to tell the editor that they are UTF-16. I am able to view the Localizable.strings files by viewing as a property list, but if I view them as Source Code, I see gibberish. I like to translate the entire localization.strings file and paste it into the editor. I don't want to have to cut and paste one line at a time in the property editor. There should be some way to tell xcode to show the file as UTF-16. Does anyone have any ideas? I tried removing the files and re-adding them. I used to get prompted for the UTF type, but it does not do this any more. A: You can find the text encoding setting for a file in the Utility area of Xcode 4.1. The utility area is the right-handside lateral area. In the utility area, look for and select the first pane, named "File Inspector". There, you will find the text encoding in the "Text Settings" block. Expand if necessary using the triangle. A: I had this same problem. I was able to work around it (without much actual investigation) by simply opening the previous string files in TextWrangler, then copy from TextWrangler and paste into XCode4's view of the string file. Things seem to be working fine as a result. A: To fix XCode 4.1 UTF-16 encoding issues: 1: Open the file you want to change 2: Put your cursor into the file, which will give the editor focus (VERY IMPORTANT). 3: Proceed to look under the Utilities Pane (very far right) for Text Settings and use the Text Encoding drop down to select UTF-16 or whatever other encoding you want. If you forget step 2, and only highlight the file in the Project Navigator, you will not see encoding options.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509024", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: two or more dots in a django template after the variable In a django template, is it possible to have two (or more) dots after a variable? For example, say I have a list of objects that I first want to use a list-index lookup for and then once I have the object, I want to call its method for getting the absolute url, should that work? For example: {% for entry in myList %} {{ entry.0.get_absolute_url }} {% endfor %} So the 0 is asking for the first item in the list which is an object, then I want to get the absolute url. It doesn't work when I try it but it doesn't return an error either. Is there a better way to accomplish what I'm trying to do? To clarify it, what's strange is that: This works: {{ singleObject.get_absolute_url }} In that case if I just try {{ singleObject }}, I get the unicode value of that object so something like: John Smith This doesn't work: {% for object in objectList %} {{ object.get_absolute_url }} {% endfor %} But in this case, if I put in {{ object }}, I no longer get the unicode value. I get: [<Name: John Smith>] (name being the name of the model) Basically, the method works when it's outside of a loop. Could there be any reason for that? A: What you are doing is perfectly acceptable in Django templates. There is no better way to accomplish what you're trying to do. A: more than one dot absolutely works. based on your comment, there is no entry.0 because entry IS the first item in the list cause you are already looping through `myList' just use entry.get_absolute_url instead but if you only want to print out the url for the first entry, forgo the for loop and just use myList.0.get_absolute_url UPDATE: there's a tip from 'the pragmatic programmer' that says: ``select’’ Isn’t Broken It is rare to find a bug in the OS or the compiler, or even a third-party product or library. The bug is most likely in the application. i think you assumed that django templates were behaving weird, when the truth is you were not building your list correctly. don't be afraid to show some of your actual code, by abstracting the problem for us, you removed the part that included the problem A: I got it. I had brackets around each item in my list like so: objectList = [['John Smith'], ['Jim Jones'], ['Bill White']] Silly me! Thanks so much for your all your input
{ "language": "en", "url": "https://stackoverflow.com/questions/7509025", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Custom Cell with Button Memory Problems I have a custom cell that contains a button in a table view. The button is used as a toggle to essentially serve as a "checkbox" for a user to check off certain items in the list. I was having the issue in which the buttons in these table cells seemed to be sharing memory locations as a result of the dequeuereusablecellwithidentifier. When a button was pressed, it would also press every 4th or 5th button in the list. I changed it to create my cells in a method into an array which then populates the tableview. This works fine for what I am trying to achieve, however it poses an issue when dealing with large row counts. The tableview itself runs quickly, but the initial load can be 3-4 seconds at times when there are over 100 rows. The iteration to create the cells and then populate it to the tableview is quite cumbersome. What other methods can you populate a tableview with custom cells and buttons while still retaining unique memory for the buttons within? Any help would be appreciated! Thanks :) A: You definitely don't want to change the way the creation of cells work- dequeuereusablecellwithidentifier is a very good thing for the reasons your seeing. The solution is that you should store the result of the button/checkbox press in a separate data structure, like an NSArray full of NSNumber. As your table scrolls and cells are reused, you reset the state of the checkbox to whatever state it should be based on your NSArray. Good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/7509030", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to implmenet the receive-response pattern in custom WCF LOB adapter So in the TryReceive() method construct the message object and return it to the engine which will be submitted to the message box. My scenario requires the receive-response message exchange pattern, in a way that adapter will send a reply back to the LOB system when the incoming received message is successfully committed to the messaggebox, where should I send the response message? Thanks. A: It looks like you want to expose some of you application schemas as a WCF service. You can do this by using the WCF Service Publishing Wizard, which you can find in the BizTalk program menu (from All Programs). If this is the case and you want further guidance then reply to this via a comment and I will expend this answer. A: WCF LOB Adapter SDK supports this scenario as mentioned here http://msdn.microsoft.com/en-us/library/bb798121%28v=bts.10%29.aspx. It seems like a combination of Synchronous Inbound and Asynchronous Outbound.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Div positioning fixed at margin-top:20px when scrolling up I have a div which I want to become fixed at 20px from the top of the window when you scroll up and 40px from the footer when you get the bottom. My code seems inconstant, there must be a better way? Page Link $(document).scroll(function () { if($(window).scrollTop() >= 345){ $('#rightShipping').css({'position' : 'fixed', 'top' : '0px'}); } if($(window).scrollTop() <= 346){ $('#rightShipping').css({'position' : '', 'top' : ''}); } console.log($(window).scrollTop()); }); A: One quick idea - I would remove the .rightCol block, leaving only the #rightShipping one with top: 20px and it parent with position: relative. And then use this code: $(document).scroll(function () { var scrollTop = $(window).scrollTop(); var offsetTop = $('#rightShipping').offset().top; var positionTop = $('#rightShipping').position().top; if (scrollTop >= offsetTop - positionTop) { $('#rightShipping').css('position', 'fixed'); } else { $('#rightShipping').css('position' : 'relative'); } }); I really don't know if this will work, as I haven't tested it and I need to get some sleep, but I hope it helps. Good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/7509034", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to hide the home controller path in action links Using the out of the box MVC application the action links under the Home controller are rendered as follows @Html.ActionLink("Home", "Index", "Home") > / @Html.ActionLink("About", "About", "Home") > /Home/About How do i make all action links that falls into the HomeController to hide the "Home" in the link paths. e.g @Html.ActionLink("About", "About", "Home") > /About @Html.ActionLink("Contact", "Contact", "Home") > /Contact @Html.ActionLink("Sitemap", "Sitemap", "Home") > /Sitemap @Html.ActionLink("Terms", "Terms", "Home") > /Terms Thanks A: You can set the controller in your route part and remove it from the url. Something like this: routes.MapRoute("", "/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional }); Look at this answer also. A: You can create different routes in the RouteConfig class as followed: routes.MapRoute( name: "AboutUs", url: "about-us", defaults: new { controller = "Home", action = "AboutUs" } ); This way, when the URL is /about-us it's going to call the AboutUs action in Home controller.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509035", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: google chart vertical text not showing in JQuery UI Dialog I am using Google Chart API to display a graph. If I display the graph in a DIV on a page it works fine. However, when I display the exact same graph in a DIV in a Dialog Box created using JQuery UI, the vertical text does not display. Everything else is fine, just the vertical text is missing from the graph in the UI Dialog Box. I have tried overriding with "vAxis:{textPosition:'out'}" which is the default with no luck.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509037", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Passing a class containing overridden virtual methods to a dll I have an application and a dll, both written in Delphi 2006. I have an class that descends from a base class and overrides several virtual methods. The class is passed to the DLL via an exported method, the exported method only knows about the base class. I call the methods on the class from within the DLL the overridden methods are not invoked. Is there something I need to do to get this to work? is is it simply not possible? A: You can't create an object in one module and call its methods in a different module. By module I mean .exe/.dll. If you wish to cross boundaries like this, then you need to use packages, COM or free functions. Packages look alluring but bind you into using the same compiler for all packages in the system. If that is not restrictive to you then go ahead and use packages. Otherwise use COM or free functions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509038", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Output friends list to json (include ID) with Mogli I'd like to convert the friends list to json (include both names and id's). Here is what I have... But it results in only a list of names. @client = Mogli::Client.new(session[:at]) @app = Mogli::Application.find(ENV["FACEBOOK_APP_ID"], @client) @user = Mogli::User.find("me", @client) @user.friends.to_json How do I also include the users ID?
{ "language": "en", "url": "https://stackoverflow.com/questions/7509039", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Vec3f class in Objective C just a quick question. I want to make a 3d game in OpenGL on a Mac but I'm not sure how to make a Vec3f class in objective c. I would really like to be able to set the class like, Vec3f *point = {1,2,3}; but still be able to treat it like a class. The only I things can think of is use a typedef struct or use regular objc setters like -(void)setX:(int)X{ x = X; } I don't know. Any Suggestions. EDIT: Just to be clear I want to be able to set the class as if it was an array. I don't need to know how to make the class, I just want to be able to know how to set the class with curly braces. Thank you. A: You can't do this in Obj-C. It doesn't provide any mechanism to do alternant initialization like that. Your best bet is to do something like this... + (id)generateVector:(float[3])vec; { //set internal structure } [Vec3f generateVector:{1,2,3}];
{ "language": "en", "url": "https://stackoverflow.com/questions/7509041", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Mysql fetch value transfer to an array Is it possible to transfer a fetch value to an array? For example in my database table I have a column named vehicle, and inside that column, it contains: vehicle1 vehicle2 vehicle3 All of that in one array. Now is it possible to transfer it to an array? (array())? Another question: How can I echo it separately? vehicle1 vehicle2 vehicle3 are all in one mysql array, how can I echo it one by one? Because if I echo the array the result would be the three vehicles. What I'm asking is that how can I echo the array that the result would be vehicle1 and if I echo it again, vehicle2. and so on. A: $vehicles = array(); $sql = "SELECT `vehicle` FROM `table` WHERE 1"; $result = mysql_query($sql); if ($result) { while (($row = mysql_fetch_array($result)) !== false) { $vehicles[] = $row['vehicle']; // or // $vehicles[] = $row; // store all columns in vehicle array } } foreach($vehicles as $vehicle) { echo "{$vehicle}<br />\n"; } You can also create an array of arrays to store multiple details from the result of your queries.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509043", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How browser's "suggestion list" works? Many websites use <input type='text'> element to get simple text data from their customers. You can configure your browser to remember the values you enter into these fields, so that it can suggest you back a list of values, to speed up your data entry experience. However, I'm seeing a strange behavior. On some fields of the same type, browser doesn't suggest anything, or suggests a different list from other fields. I've checked all fields and all of them are of the same <input type='text'> type. Does anybody know how browser differentiates between different lists (or no list) for the same HTML form control? A: There's an attribute on form elements that allows them to semantically specify their intended content (I believe its the V_Card attribute). The following page gives a brief explanation and a table of acceptable values: http://microformats.org/wiki/hcard-input-formats
{ "language": "en", "url": "https://stackoverflow.com/questions/7509047", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using NInject to find a class, but constructing the class with your own parameters I know this is not good practice. Here is some code that sort of demonstrates the problem (but doesn't actually work): public interface IBar {} public interface Bar : IBar {} public interface IFoo {} public class Foo : IFoo { public Foo(IBar bar) { } } public class InjectionModule : NinjectModule { public override void Load() { Bind<IFoo>().To<Foo>(); } } public class MyApp { public void DoSomething() { // Get a foo with a particular bar var foo1 = Kernel.Get<IFoo>(new Bar()); // Get another foo with a different bar var foo2 = Kernel.Get<IFoo>(new Bar()); } } So what I am trying to do is to use NInject to bind IFoo to Foo, but have my app supply the Bar argument to the constructor at runtime, rather than the usual practice where NInject resolves the IBar dependency. A: var foo1 = Kernel.Get<IFoo>(new ConstructorArgument("bar", new Bar()));
{ "language": "en", "url": "https://stackoverflow.com/questions/7509049", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: The difference between type casting and using std::move()? I am just a bit curious about the new function std::move() that has just been added into the newest C++ standard. Finished reading an article about it and found out that the function's definition is namespace std { template <class T> inline typename remove_reference<T>::type&& move(T&& x) { return x; } } This seems like it doesn't have any difference between calling std::move and using casting. For example here, class NPC{ int m_number1; int m_number2; public: NPC() : m_number1(1), m_number2(2) { cout << "NPC Constructor called!" << endl; } NPC(NPC&& _npc) : m_number1(_npc.m_number1), m_number2(_npc.m_number2) { _npc.m_number1 = 0; _npc.m_number2 = 0; cout << "NPC Move Constructor called!" << endl; } }; int main() { NPC n1; NPC n2 = std::move(n1); cout << "----------------" << endl; NPC n3; NPC n4 = (NPC&&)n3; return 0; } Is it right to think that there is basically no difference? Well, I am pretty much sure that I am right but also know that being too confident always backfires. Thanks in advance! A: std::move is defined as a specialized cast: static_cast<typename remove_reference<T>::type&&>(t) You could do this if you really want. But it would be much shorter and obvious to everyone what you're doing if you just use std::move. The rules around && casting are weird, so it's best to just use move and forward when that's what you mean. A: There is no difference in functionality, but there is a difference in readability. Just as while loops are preferred to gotos, and C++ style casts are preferred to C style casts, std::move is preferred to casting because it is a less general tool, and so it is easier to understand what it is doing without needing investigate the structure of the code any further. A: Yes, std::move does nothing in terms of functionality. Its purpose is to convert an lvalue into an xvalue, which makes the result movable. It's better than using a cast because it makes the purpose clear.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509050", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Is it safe to have a hidden display of mysql query on your live site I am doing a project with a team and some of my team make a hidden display to view the mysql query.Is it safe to do this on live?It's been a month that the site has it.Is it safe to use this kind of technique? <div style="display: none;"> SELECT * FROM <statement> LEFT JOIN <statement> WHERE `username` = 'admin' ORDER BY <statement> DESC </div> <div style="display: none;"> SELECT * FROM <statement> LEFT JOIN <statement> WHERE <statement> ORDER BY <statement> LIMIT 10 </div> A: That is simply a horrific idea. You should not let info like that be available. A: This is definitely not a good idea. It gives attackers a substantial amount of information on how your database is structured. If they find an SQL injection hole somewhere, they've got a nice roadmap of exactly what queries to run to completely screw with your database. This is what development environments are for. A: The other posts are dead on, but I'd like to add that if the "technique" of hiding the query that you're referring to is to use css to set the display to "none", then no it's not safe. It assumes that any attacker looking at your site is too dumb to figure out how to view the source. I guarantee you that if someone is smart enough to know how to perform the sql injection attack in the first place, they know how to open a page in a browser and view the source. Not to mention that bots that are scanning for vulnerabilities see only the source, setting the display property is pointless. A: I've certainly done it before for brief testing in time-sensitive scenarios where a problem needs to be debugged quickly. But I would avoid if it all possible. However, I should point out that this should (in theory) not be a security concern. Information about your database schema is really only useful if an attacker has a way to execute SQL commands on your database. There are certainly other possible risks, but if your security is in good shape otherwise, the risks should be minimal. Just to reiterate though, I'm not advocating this approach as it can still come back to bite you. A: I'm not sure why you'd even want to do this, but if you wanted to check in browser what SQL queries are being done you should probably look at FirePHP (http://www.firephp.org/). It's an extension for the well known firebug firefox extension (extenception...) that lets you view what queries are being done by your code from your browser. You do have to install some server side stuff for that though. Other than that I don't think it should be THAT much of a problem if you can't actually execute arbitrary SQL queries but I do think that you will be more of a target. If I'd be wearing a black hat and saw that someone printed their SQL queries in the source I'd be much quicker to ponder around than with other sites that don't do this, because they probably do other weird (stupid) stuff.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509055", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Edit the nodes in a binary tree in Java Okay. I have a binary tree, and this is what I want to do with it: For each node in original tree: If it's not a leaf, replace it with a leaf node. Do a calculation on the original tree updated with the removed branch. Revert the node back to how it was (so now the tree is the same as at the beginning). The problem is this: I am traversing the tree using a stack. If I change the stack.pop() node to a leaf, this does NOT remove any branches in the original tree. It's the same reasoning behind why you can do: int x=1 int y=x y++ And x still equals 1. There's a technical term for this but I forgot it. So how can I edit the nodes in an original tree and still traverse it? This is basically what I'm doing to traverse the tree right now: public void iterativePreorder(Node root) { Stack nodes = new Stack(); nodes.push(root); Node currentNode; while (!nodes.isEmpty()) { currentNode = nodes.pop(); Node right = currentNode.right(); if (right != null) { nodes.push(right); } Node left = currentNode.left(); if (left != null) { nodes.push(left); } //This is where you do operations on the currentNode } } A: From what I can tell from your question, for every Node you want to calculate something about the tree as if that node was a leaf. To do this there is no reason to actually make that node a leaf and then reattach it. Instead, your logic can simply remember which node to treat as a leaf for each computation. Traverse the tree, and for each Node, let's call it outerCurrentNode, once again traverse the tree doing your calculation - but now for each Node, let's call it innerCurrentNode, test to see if outerCurrentNode == innerCurrentNode. If the test returns true, treat that innerCurrentNode as if it's a leaf, ignoring its children. EDIT: Here's a mock up of what I'm suggesting (untested): //entry point - called from directing code public void iterativePreorder(Node root) { iterativePreorderKernel(root, root); } //recursive method - keeps track of root in addition to current Node private void iterativePreorderKernel(Node root, Node current) { if (current.left() != null) { iterativePreorderKernel(root, current.left()); } if (current.right() != null) { iterativePreorderKernel(root, current.right()); } //for each Node in the tree, do calculations on the entire tree, pretending //the current Node is a leaf doCalculation(root, current); } //calculation method (also recursive) - takes a current Node, plus //the Node to treat as a leaf public void doCalculation(Node innerCurrent, Node pretendLeaf) { //do calculation with inner current node if (innerCurrent != pretendLeaf) { if (innerCurrent.left() != null) { doCalculation(innerCurrent.left(), pretendLeaf); } if (innerCurrent.right() != null) { doCalculation(innerCurrent.right(), pretendLeaf); } } } I'm using recursion instead of a Stack, but either will work. iterativePreorder() does a traversal, calling doCalculation() for each Node, passing it in along with the root (to keep track of the entire tree). That method then does its own traversal, doing your calculation, but stopping short when it reaches the specially marked Node.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509056", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add new row into listview? i have a listview with column ID and Barcode.. how to insert a new row into the listview when 'Add' button is click? The new data that we insert will also be saved into my database. btw, i am using Visual Studio 2008 C# A: Insert in Listview ListViewItem lstview = new ListViewItem(yourColumnIDValue); listView1.Items.Add(lstview); lstview.SubItems.Add(yourBarcodeValue); Insert in your DB. INSERT INTO yourtable(ColumnID,Barcode) VALUES (yourColumnIDValue,yourBarcodeValue);
{ "language": "en", "url": "https://stackoverflow.com/questions/7509059", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Failed to Set Breakpoint in WinDbg My workflow follows. * *Configure the symbol file path and source code file path for WinDbg. *Open one source code file to be debugged later. *Press F9 and try to set breakpoint in the source code. *WinDbg pops up an error dialog, saying 'Debuggee must be stopped before breakpoints can be modified.' Who can tell me why? My WinDbg version is 6.11.0001.404 (X86), Windows XP 64-bit. I am debugging a dll from within very complicated runtime system. I wrote a simple exe and click to open it. Immediately after opening it, I open the source code file and set one breakpoint. It works in this case! A: The hint is in the error, "Debuggee must be stopped before breakpoints can be modified". You have to break into the target process with Debug->Break before WinDBG will let you set a breakpoint. When you launch an EXE under WinDBG is starts off broken in, so you can set the breakpoint. -scott
{ "language": "en", "url": "https://stackoverflow.com/questions/7509062", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: use of mathematical annotation as factor in R I refer to my previous question, and want to know more about characteristics of factor in R. Let say I have a dataset like this: temp <- data.frame(x=letters[1:5], y=1:5) plot(temp) I can change the label of x easily to another character: levels(temp[,"x"]) <- letters[6:10] But if I want to change it into some expression levels(temp[,"x"]) <- c(expression(x>=1), expression(x>=2), expression(x>=3), expression(x>=4), expression(x>=5)) The >= sign will not change accordingly in the plot. And I found that class(levels(temp[,"x"])) is character, but expression(x>=1) is not. If I want to add some mathematical annotation as factor, what can I do? A: I do not see any levels arguments in ggplot and assigning levels to a character vector should not work. If you are trying to assign expression vectors you should just use one expression call and separate the arguments by commas and you should use the labels argument in a scale function: p <- qplot(1:10, 10:1)+ scale_y_continuous( breaks= 1:10, labels=expression( x>= 1, x>=2, x>=3, x>= 4,x>=5, x>= 6, x>=7, x>= 8,x>=9, x>= 10) ) p A: I would just leave them as character strings levels(temp[,"x"]) <- paste("x>=", 1:5, sep="") If you then want to include them as axis labels, you could do something like the following to convert them to expressions: lev.as.expr <- parse(text=levels(temp[,"x"])) For your plot, you could then do: plot(temp, xaxt="n") axis(side=1, at=1:5, labels=lev.as.expr) A: Expression is used to generate text for plots and output but can't be the variable names per se. You'd have to use the axis() command to generate your own labels. Because it can evaluate expressions you could try... plot(temp, xaxt = 'n') s <- paste('x>', 1:5, sep = '=') axis(1, 1:5, parse(text = s))
{ "language": "en", "url": "https://stackoverflow.com/questions/7509067", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Replace the default MessageBox When I use Ext.MessageBox.show({...}) it show the box like IMG2 default. I want to use the box like IMG1 and how could I replace it. Thanks!!! A: you should use loadMask for your extjs component. // Basic mask: var myMask = new Ext.LoadMask(Ext.getBody(), {msg:"Please wait..."}); myMask.show();
{ "language": "en", "url": "https://stackoverflow.com/questions/7509072", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# Linq for files user has read access to How would I use Linq on list.Items = directoryInfo.GetFiles("\\server\share\folder\"); to include only the files the user has read access to? ... So far only suggestions are using try/catches, or APIs that are obsolete in .NET 4.0? I'd prefer something to read the ACL's and see if the specific user or a group the user is a member of has been granted read access. I'm trying to do this for simplified management of granting reports to users on a website that won't be high traffic, so the logic that "who knows if you can actually read it when you try to open the file" doesn't pertain to this case. I sense that Microsoft should really make this task easier. A: just try this out .should work .haven't tested though var fw = from f in new DirectoryInfo("C:\\Users\\User\\Downloads\\").GetFiles() where SecurityManager.IsGranted(new FileIOPermission (FileIOPermissionAccess.Write, f.FullName)) select f; EDIT if it is just read only files then try this var fe = from f in new DirectoryInfo("C:\\Users\\ashley\\Downloads\\").GetFiles() where f.IsReadOnly==true select f A: You run the risk of a race condition if you check for read permission prior to opening the file. If you're attempting to read all of the files you have access to in a folder, better to just try opening each one and catch the UnauthorizedAccessException. See: * *how can you easily check if access is denied for a file in .NET? *How do you check for permissions to write to a directory or file? A: Note: I haven't tested it, but in theory it should work First, define a predicate to determine read access bool CanRead(FileInfo file) { try { file.GetAccessControl(); //Read and write access; return true; } catch (UnauthorizedAccessException uae) { if (uae.Message.Contains("read-only")) { //read-only access return true; } return false; } } Then, it should be a simple case of using a where clause in a linq query from file in directoryInfo.GetFiles("\\server\share\folder\") where HaveAccess(f) == true select f; A: Tested and working, but will return false if the file is in use void Main() { var directoryInfo = new DirectoryInfo(@"C:\"); var currentUser = WindowsIdentity.GetCurrent(); var files = directoryInfo.GetFiles(".").Where(f => CanRead(currentUser, f.FullName)); } private bool CanRead(WindowsIdentity user, string filePath) { if(!File.Exists(filePath)) return false; try { var fileSecurity = File.GetAccessControl(filePath, AccessControlSections.Access); foreach(FileSystemAccessRule fsRule in fileSecurity.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier))) { foreach(var usrGroup in user.Groups) { if(fsRule.IdentityReference.Value == usrGroup.Value) return true; } } } catch (InvalidOperationException) { //File is in use return false; } return false; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7509075", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Google Plus Application Dev Language Does anyone know what language the google plus apps need to be written in? A: The APIs, themselves, are REST-ful web-based APIs that simply use standard protocols such as OAuth that are built on top of HTTP, HTTPS, JSON, XML, and other web standards. Code written in a variety of languages can use these APIs by issuing HTTPS and HTTP requests. Google has a bunch of "client libraries" written in a variety of different languages that support their various web-based APIs. For a list of existing client-libraries that support (some of) the Google+ APIs, see: http://developers.google.com/+/downloads A: As with Facebook, you can access the Google Plus APIs with any programming language.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509076", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Testing defaults in Rails ActionMailer How are you testing these lines in your ActionMailer specs? default 'HEADER' => Proc.new { "information" }, :cc => "asdf@asdf.com", :from => "asdf@asdf.com", :to => "asdf@asdf.com" A: Something like that: # notifier_spec.rb require "spec_helper" describe Notifier do describe "welcome" do let(:user) { Factory :user } let(:mail) { Notifier.welcome(user) } it "renders the headers" do mail.content_type.should eq('text/plain; charset=UTF-8') mail.subject.should eq("Welcome") mail.cc.should eq(["zombie@example.com"]) mail.from.should eq(["zombie@example.com"]) mail.to.should eq([user.email]) end it "renders the body" do mail.body.encoded.should match("Hi") end end end This is how Ryan Bates (= whole buncha people) does it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509078", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: CSS for setting overflow to scroll not working I have a div using the following class: div.textStatement { height: 70px; overflow: hidden; } When the user clicks a link ('Show More'), the div expands to show more text and the 'overflow' should get set to 'scroll' so that the user can read all the text, in the event there is more text than the height of the div will show. However, the reference to the 'overflow' property of the div is coming back 'undefined' so that I can't set it to 'scroll.' Any idea why the ref to the div's overflow is coming back 'undefined'? I think that would fix the problem (and make the scrollbars show up). Here's the div: <asp:Panel ID="textStatement" class="textStatement" runat="server"></asp:Panel> <label id="candidateStatementShowMoreLess" class="MoreLess" onclick="ShowMoreLess(this)">Show More</label> Here's the javascript (using jQuery): var IsStatementExpanded = false; var IsDescriptionExpanded = false; function ShowMoreLess(moreLessLink) { var section = $(moreLessLink).prev("div"); var sectionId = $(section).attr("id"); var collapsedHeight = 70; var expandedHeight = 300; if (section.height() == collapsedHeight) { section.animate({ height: expandedHeight }, 500, function () { $(moreLessLink).html("Show Less"); // ***** This should be setting the overflow to scroll on the div, but isn't, as "attr" is coming back undefined. ***** section.attr("overflow", "scroll"); }); if (sectionId == "textStatement") { IsStatementExpanded = true; } else if (sectionId == "textDescription") { IsDescriptionExpanded = true; } } else { section.animate({ height: collapsedHeight }, 500, function () { $(moreLessLink).html("Show More"); // ***** This could have the same problem as above, but when the user collapses the div. ***** section.attr("overflow", "hidden"); }); if (sectionId == "textStatement") { IsStatementExpanded = false; } else if (sectionId == "textDescription") { IsDescriptionExpanded = false; } } } A: section.attr("overflow", "scroll"); is incorrect. It needs to be section.css("overflow", "scroll");
{ "language": "en", "url": "https://stackoverflow.com/questions/7509080", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Tab requirement using CSS and Javascript I have the below requirement: Front end for a big database which stores details about the sports students are in a school. For example student xyz plays cricket so database will store cricket details for him, student pqr plays soccer so database will store soccer details for him and so on. The main screen is divided into two sections. The left section is a search section with several criteria user can input. On clicking search, result will be published in the right section as a summary. For e.g. if searching for x resulted in 5 students, then the summary result will be 5 rows. Now clicking on a specific student on the summary result should fetch all the other details specific to him and should publish it as new tabs in the same section. Like Occupation in One tab, his sports details in other tab. 1) How to achieve this using CSS and Javascript? 2) How to keep the other tabs disabled? For eg. soccer tab should not get enabled for student playing cricket. I am extremely new in CSS and JS, so may be my requirement is not as complex as I feel. But I definitely require a starting point. A: Use a separate <div> section for each tab, and specify a class attribute on each div that describes how it is being used. You can hide/show a div by modifying its style.visibility property (you set it to 'hidden' to hide the div and, for most situations, 'block' to display the div). You can use CSS to apply different styling to each div (such as its location on the page). Personally, I would divide this up into three different tasks. The first task is setting the layout of the page to look right, using fake data (e.g. create a function that "fetches" the data, but actually just gives back canned data). The second task is provide request handlers that can return raw, unstyled data (preferably in JSON format) based on the data in the database. The third, final task is to connect the JavaScript in your user interface to actually fetch the data using XHR requests to these endpoints, and passing along the JSON response appropriately instead of passing along fake data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509089", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create certificate object using PKCS 11 I am currently working on a project using PKCS#11 to interact with an USB Token. I have read PKCS #11 v2.20: Cryptographic Token Interface Standard and I can create other objects using the C_CreateObject function, but when I create a Certificate with this code then the return code is always CKR_DOMAIN_PARAMS_INVALID. Can anybody tell my why I get this error? And if you have example in C or C++ please post it. A: The term 'domain parameters' refers to the parameters associated with a cryptographic algorithm, such as DSA or Diffie-Hellman. Does the USB token support the key lengths and algorithms used your certificate? Were the domain parameters generated locally? Does the USB support externally provided domain parameters? Without seeing any code, it's difficult to be more helpful.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: License of fonts included with Windows? I'm wondering what is the license of the fonts included with Windows. Does anybody know where I could find the EULA for them? In general, can I freely use these fonts in my open source software? In general, I know I cannot distribute the font file itself, but how about simply displaying some text with this font? For example, Arial is used in many websites, I guess these websites don't pay some extra license fee to Microsoft? A: You are free to use the fonts supplied with Windows, free to write software that uses them, but you cannot distribute them. A: The Arial wikipedia article describes the licensing terms of Microsoft fonts. And, it also specifies free alternatives available that are metrically equivalent to Arial. Liberation Sans is a good choice IMO. Look at relevant wiki articles to know all the free alternatives available. Most of the Windows fonts are licensed to Ascender corporation. They now provide license for software and hardware developers to use them. See Type Foundry: Microsoft for more information, and the fonts available. In addition to that, if you go to right-click -> properties, there's a tab called license. It provides the information about licensing terms as well. When it comes to use of fonts like Arial in websites, I think it's allowed because the website itself doesn't embed the font, but merely specifies the font name. It's the browser that does the mapping. If you are talking about a stand-alone software, you need to have a closer look.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509100", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Set selected row for a given value in UIPickerView iPhone In my app, I ask a worker to choose a letter from the alphabet (for example A) and the alphabet will have some explications that will appear in a UIPickerView with 3 # rows. I want my UIPickerView to be display contents based on the indicator that has been chosen by a worker. How do I do this? A: selection. in this case, it means showing the appropriate row in the middle - (void)selectRow:(NSInteger)row inComponent:(NSInteger)component animated:(BOOL)animated; scrolls the specified row to center. please provide some code so That I can Get What exact issue is
{ "language": "en", "url": "https://stackoverflow.com/questions/7509101", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Animate the number change in UILabel I have placed a Cocoa Touch UILabel, which displays numbers. What I want is to animate the text in UILabel when number changed. So that the user can be easier to notice the number is changing. The animation can be very simple, for example, when the text is changed, it first zooms to a bigger size, and then zooms back to normal size. It seems I can only animate the font size. any suggestions? Thanks A: Why dont you do this scale increase and finally decrease back to normal on the UILabel itself? Create scale animation in UILabel's CALayer - CAKeyframeAnimation *scaleAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform"]; NSArray *scaleValues = [NSArray arrayWithObjects: [NSValue valueWithCATransform3D:CATransform3DScale(v.layer.transform, 1, 1, 1)], [NSValue valueWithCATransform3D:CATransform3DScale(v.layer.transform, 1.1, 1.1, 1)], [NSValue valueWithCATransform3D:CATransform3DScale(v.layer.transform, 1, 1, 1)], nil]; [scaleAnimation setValues:scaleValues]; scaleAnimation.fillMode = kCAFillModeForwards; scaleAnimation.removedOnCompletion = NO; [yourUILabel.layer addAnimation:scaleAnimation forKey:@"scale"]; A: How about fade out the previous uilabel, change it, then fade it back in (using the alpha property)?
{ "language": "en", "url": "https://stackoverflow.com/questions/7509108", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Only some png images display, others don't for no apparent reason I have some code which randomly displays a given .png image and its title.The title logic is working fine. However, for some reason, only two of the four images display. I've tried changing the order just in case, but only those two images, pic_c and pic_d, ever get displayed. I've also checked the spelling, and that the files are in resources and exist on the file system. Here's the code which displays the image: NSMutableArray *fileNameArray = [[NSMutableArray alloc] init]; [fileNameArray addObject:[NSString stringWithFormat: @"pic_a"]]; [fileNameArray addObject:[NSString stringWithFormat: @"pic_b"]]; [fileNameArray addObject:[NSString stringWithFormat: @"pic_c"]]; [fileNameArray addObject:[NSString stringWithFormat: @"pic_d"]]; NSMutableArray *titleArray = [[NSMutableArray alloc] init]; [titleArray addObject:[NSString stringWithFormat: @"pic a"]]; [titleArray addObject:[NSString stringWithFormat: @"pic b"]]; [titleArray addObject:[NSString stringWithFormat: @"pic c"]]; [titleArray addObject:[NSString stringWithFormat: @"pic d"]]; int index = arc4random() % [fileNameArray count]; NSString *pictureName = [titleArray objectAtIndex:index]; art_title.text = pictureName; NSString* imagePath = [ [ NSBundle mainBundle] pathForResource:pictureName ofType:@"png"]; UIImage *img = [ UIImage imageWithContentsOfFile: imagePath]; if (img != nil) { // Image was loaded successfully. [imageView setImage:img]; [imageView setUserInteractionEnabled:NO]; [img release]; // Release the image now that we have a UIImageView that contains it. } [super viewDidLoad]; [fileNameArray release]; [titleArray release]; } Any idea why this might be happening? Recent information: If I remove the titleArray, and use the file name array only, all the images show up. However, I'd still like to be able to use the titleArray. A: What are your image files actually called? In the code above you don't actually do anything with finleNameArray except count it. You use the values from titleArray to get the image resource. I would think you need the following code in there: NSString *filename = [fileNameArray objectAtIndex:index]; Then change your imagePath to use this instead of pictureName.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509109", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Do I need to set download speed limit for concurent downloads (using cURL) or they will take equal shares? My website (run under ubuntu 10,04) enables users to grab files from web links .. Do I need to set a download rate limit per single file , so all can download at the same time ? And also , do I need to set a global download limit (for all files together) so that my server connection can handle other requests of downloading files directly from my server , browsing my website ...etc ? Thank you :) A: The rate limit curl supports is set per "handle", which makes it per single transfer. Networks in general are designed to handle many connections sharing a tight shared resource, so in most situations you won't need to limit any transfer rates at all.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cython & Hadoopy compiling error.. any ideas on a fix? I'm trying to run Hadoopy, but am getting a compiling error on OS X: ImportError: Building module failed: ["CompileError: command 'llvm-gcc-4.2' failed with exit status 1\n" I have /Developer/usr/bin in my $PATH, and am running latest version of XCode on OS X Lion 10.7. Cython was installed via easy_install. Full output: >>> import pyximport; pyximport.install() >>> import hadoopy /Users/dolan/.pyxbld/temp.macosx-10.7-intel-2.7/pyrex/hadoopy/_main.c:236:22: error: getdelim.h: No such file or directory /Users/dolan/.pyxbld/temp.macosx-10.7-intel-2.7/pyrex/hadoopy/_main.c:236:22: error: getdelim.h: No such file or directory /Users/dolan/.pyxbld/temp.macosx-10.7-intel-2.7/pyrex/hadoopy/_main.c: In function ‘__pyx_f_7hadoopy_5_main_11HadoopyTask_read_offset_value_text’: /Users/dolan/.pyxbld/temp.macosx-10.7-intel-2.7/pyrex/hadoopy/_main.c:4399: warning: implicit conversion shortens 64-bit value into a 32-bit value lipo: can't open input file: /var/folders/8b/n0j5pn_13qn_x8p2v4f848zh0000gn/T//ccC8x2Ex.out (No such file or directory) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Library/Python/2.7/site-packages/hadoopy/__init__.py", line 22, in <module> from _main import run, print_doc_quit File "/Library/Python/2.7/site-packages/Cython-0.15.1-py2.7-macosx-10.7-intel.egg/pyximport/pyximport.py", line 335, in load_module self.pyxbuild_dir) File "/Library/Python/2.7/site-packages/Cython-0.15.1-py2.7-macosx-10.7-intel.egg/pyximport/pyximport.py", line 183, in load_module so_path = build_module(name, pyxfilename, pyxbuild_dir) File "/Library/Python/2.7/site-packages/Cython-0.15.1-py2.7-macosx-10.7-intel.egg/pyximport/pyximport.py", line 167, in build_module reload_support=pyxargs.reload_support) File "/Library/Python/2.7/site-packages/Cython-0.15.1-py2.7-macosx-10.7-intel.egg/pyximport/pyxbuild.py", line 85, in pyx_to_dll dist.run_commands() File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/dist.py", line 953, in run_commands self.run_command(cmd) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/dist.py", line 972, in run_command cmd_obj.run() File "/Library/Python/2.7/site-packages/Cython-0.15.1-py2.7-macosx-10.7-intel.egg/Cython/Distutils/build_ext.py", line 135, in run _build_ext.build_ext.run(self) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/command/build_ext.py", line 340, in run self.build_extensions() File "/Library/Python/2.7/site-packages/Cython-0.15.1-py2.7-macosx-10.7-intel.egg/Cython/Distutils/build_ext.py", line 143, in build_extensions self.build_extension(ext) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/command/build_ext.py", line 499, in build_extension depends=ext.depends) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/ccompiler.py", line 624, in compile self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/unixccompiler.py", line 180, in _compile raise CompileError, msg ImportError: Building module failed: ["CompileError: command 'llvm-gcc-4.2' failed with exit status 1\n" A: For me it was an installation issue and i had fixed it sometime back using below mentioned steps: * *pip install argparse *git clone https://github.com/bwhite/hadoopy.git *cd hadoopy *python setup.py install A: Instead of using pyximport, build the extension modules in place with python setup.py build_ext --inplace (or install for in-place development with python setup.py develop, or just a regular install via python setup.py install). For packages you almost always want to run the setup, which will properly configure the compilation environment, build, and installation process. pyximport is good for your personal scripts if you're using Cython to speed up your code (e.g. for scientific computing). Even then you might need to bring in other libraries, and build from multiple sources. In that case, you can use a pyxbld file to set up the sources and include_dirs. For example, say you have foo.pyx, then you can place build instructions in a foo.pyxbld in the same directory. For example: #foo.pyxbld def make_ext(modname, pyxfilename): from distutils.extension import Extension return Extension(name = modname, sources=[pyxfilename, 'bar.c'], include_dirs=['/myinclude'] ) def make_setup_args(): return dict(script_args=["--compiler=mingw32"]) Now using foo is as simple as the following: import pyximport pyximport.install() import foo Presuming there's no compilation errors, it's virtually transparent but for the delay the first time you import the module. Subsequent imports will look for the built extension in the .pyxbld subdirectory of your home/profile directory.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509117", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I force the rerun of the app's initial rule? I have an app that has a login/logout functionality. Upon logout, I am clearing the entity variable. How do I force the app to rerun the initial rule and display the login form? A: You can have the initial rule run again by carefully crafting the select statement of the initial rule. Assuming that you are running the app in the browser, the initial rule fires on web pageview, and the logout click fires a custom logout web event, here is what I would do: rule initial_rule { select when web pageview "awesome*Regex(here)" or web logout pre { // do cool stuff here } { // fire actions here } // postlude block of choice here }
{ "language": "en", "url": "https://stackoverflow.com/questions/7509118", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MySQL: Using a reference id, see if data matches across that id I have the following table id | data | reference_id 1 Jacob 3 2 Apples 3 3 Henry 4 4 Pie 4 5 Jacob 5 6 Pears 5 What I'm trying to do is build a query that checks if data exists in the same reference_id given the data. So basically: SELECT COUNT(*) WHERE data='Jacob' AND data='Apples' AND ...(reference_id's are the same) A: SELECT COUNT(*) WHERE data='Jacob' AND data='Apples' GROUP BY reference_id;
{ "language": "en", "url": "https://stackoverflow.com/questions/7509120", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: In XAML is it possible to set a ResourceDictionary and Style in UserControl.Resources side-by-side? Is it possible to set an inline style when I've already set a ResourceDictionary? Here is what I've already set... <UserControl.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="pack://application:,,,/My.Project.Common.Desktop;component/Themes/StandardStyles.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </UserControl.Resources> Here are the styles I need to add to the UserControl.Resources node... <Style x:Key="MessageErrorIcon" TargetType="{x:Type Rectangle}"> <Style.Triggers> <DataTrigger Binding="{Binding Icon}" Value="Asterisk"> <Setter Property="Fill" Value="{DynamicResource MessageOverlayInformationIcon}"/> </DataTrigger> <DataTrigger Binding="{Binding Icon}" Value="Error"> <Setter Property="Fill" Value="{DynamicResource MessageOverlayErrorIcon}"/> </DataTrigger> <DataTrigger Binding="{Binding Icon}" Value="Exclamation"> <Setter Property="Fill" Value="{DynamicResource MessageOverlayExclamationIcon}"/> </DataTrigger> <DataTrigger Binding="{Binding Icon}" Value="Hand"> <Setter Property="Fill" Value="{DynamicResource MessageOverlayErrorIcon}"/> </DataTrigger> <DataTrigger Binding="{Binding Icon}" Value="Information"> <Setter Property="Fill" Value="{DynamicResource MessageOverlayInformationIcon}"/> </DataTrigger> <DataTrigger Binding="{Binding Icon}" Value="Question"> <Setter Property="Fill" Value="{DynamicResource MessageOverlayQuestionIcon}"/> </DataTrigger> <DataTrigger Binding="{Binding Icon}" Value="Stop"> <Setter Property="Fill" Value="{DynamicResource MessageOverlayErrorIcon}"/> </DataTrigger> <DataTrigger Binding="{Binding Icon}" Value="Warning"> <Setter Property="Fill" Value="{DynamicResource MessageOverlayExclamationIcon}"/> </DataTrigger> </Style.Triggers> </Style> I need it to be set these styles at a UserControl level because they are bound to the data context. How do I do this? A: you can add resources like this <UserControl.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="pack://application:,,,/My.Project.Common.Desktop;component/Themes/StandardStyles.xaml" /> </ResourceDictionary.MergedDictionaries> <Style x:Key="MessageErrorIcon" TargetType="{x:Type Rectangle}"> <Style.Triggers> <DataTrigger Binding="{Binding Icon}" Value="Asterisk"> <Setter Property="Fill" Value="{DynamicResource MessageOverlayInformationIcon}" /> </DataTrigger> <DataTrigger Binding="{Binding Icon}" Value="Error"> <Setter Property="Fill" Value="{DynamicResource MessageOverlayErrorIcon}" /> </DataTrigger> <DataTrigger Binding="{Binding Icon}" Value="Exclamation"> <Setter Property="Fill" Value="{DynamicResource MessageOverlayExclamationIcon}" /> </DataTrigger> <DataTrigger Binding="{Binding Icon}" Value="Hand"> <Setter Property="Fill" Value="{DynamicResource MessageOverlayErrorIcon}" /> </DataTrigger> <DataTrigger Binding="{Binding Icon}" Value="Information"> <Setter Property="Fill" Value="{DynamicResource MessageOverlayInformationIcon}" /> </DataTrigger> <DataTrigger Binding="{Binding Icon}" Value="Question"> <Setter Property="Fill" Value="{DynamicResource MessageOverlayQuestionIcon}" /> </DataTrigger> <DataTrigger Binding="{Binding Icon}" Value="Stop"> <Setter Property="Fill" Value="{DynamicResource MessageOverlayErrorIcon}" /> </DataTrigger> <DataTrigger Binding="{Binding Icon}" Value="Warning"> <Setter Property="Fill" Value="{DynamicResource MessageOverlayExclamationIcon}" /> </DataTrigger> </Style.Triggers> </Style> </ResourceDictionary> </UserControl.Resources>
{ "language": "en", "url": "https://stackoverflow.com/questions/7509121", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Any sure fire way to check file existence on Linux NFS? I am working on a Java program that requires to check the existence of files. Well, simple enough, the code make use calls to File.exists() for checking file existence. And the problem I have is, it reports false positive. That means the file does not actually exist but exists() method returns true. No exception was captured (at least no exception like "Stale NFS handle"). The program even managed to read the file through InputStream, getting 0 bytes as expected and yet no exception. The target directory is a Linux NFS. And I am 100% sure that the file being looked for never exists. I know there are known bugs (kind of API limitation) exist for java.io.File.exists(). So I've then added another way round by checking file existence using Linux command ls. Instead of making call to File.exists() the Java code now runs a Linux command to ls the target file. If exit code is 0, file exists. Otherwise, file does not exist. The number of times the issue is hit seems to be reduced with the introduction of the trick, but still pops. Again, no error was captured anywhere (stdout this time). That means the problem is so serious that even native Linux command won't fix for 100% of the time. So there are couple of questions around: * *I believe Java's well known issue on File.exists() is about reporting false negative. Where file was reported to not exist but in fact does exist. As the API does not throws IOException for File.exists(), it choose to swallow the Exception in the case calls to OS's underlying native functions failed e.g. NFS timeout. But then this does not explain the false positive case I am having, given that the file never exist. Any throw on this one? *My understanding on Linux ls exit code is, 0 means okay, equivalent to file exists. Is this understanding wrong? The man page of ls is not so clear on explaining the meaning of exit code: Exit status is 0 if OK, 1 if minor problems, 2 if serious trouble. *All right, back to subject. Any surefire way to check File existence with Java on Linux? Before we see JDK7 with NIO2 officially released. A: Here is a JUnit test that shows the problem and some Java Code that actually tries to read the file. The problem happens e.g. using Samba on OSX Mavericks. A possible reason is explaned by the statement in: http://appleinsider.com/articles/13/06/11/apple-shifts-from-afp-file-sharing-to-smb2-in-os-x-109-mavericks It aggressively caches file and folder properties and uses opportunistic locking to enable better caching of data. Please find below a checkFile that will actually attempt to read a few bytes and forcing a true file access to avoid the caching misbehaviour ... JUnit test: /** * test file exists function on Network drive replace the testfile name and ssh computer * with your actual environment * @throws Exception */ @Test public void testFileExistsOnNetworkDrive() throws Exception { String testFileName="/Volumes/bitplan/tmp/testFileExists.txt"; File testFile=new File(testFileName); testFile.delete(); for (int i=0;i<10;i++) { Thread.sleep(50); System.out.println(""+i+":"+OCRJob.checkExists(testFile)); switch (i) { case 3: // FileUtils.writeStringToFile(testFile, "here we go"); Runtime.getRuntime().exec("/usr/bin/ssh phobos /usr/bin/touch "+testFileName); break; } } } checkExists source code: /** * check if the given file exists * @param f * @return true if file exists */ public static boolean checkExists(File f) { try { byte[] buffer = new byte[4]; InputStream is = new FileInputStream(f); if (is.read(buffer) != buffer.length) { // do something } is.close(); return true; } catch (java.io.IOException fnfe) { } return false; } A: JDK7 was released a few months ago. There are exists and notExists methods in the Files class but they return a boolean rather than throwing an exception. If you really want an exception then use FileSystems.getDefault().provider().checkAccess(path) and it will throw an exception if the file does not exist. A: If you need to be robust, try to read the file - and fail gracefully if the file is not there (or there is a permission or other problem). This applies to any other language than Java as well. The only safe way to tell if the file exist and you can read from it is to actually read a data from the file. Regardless of a file system - local, or remote. The reason is a race condition which can occur right after you get success from checkAccess(path): check, then open file, and you find it suddenly does not exist. Some other thread (or another remote client) may have removed it, or has acquired an exclusive lock. So don't bother checking access, but rather try to read the file. Spending time in running ls just makes race condition window easier to fit.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509123", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Do/Undo using command pattern in Python I have read that using command pattern is one of the most popular ways to accomplish do/undo functionality. In fact, I have seen that it's possible to stack a bunch of actions and reverse them in order to reach a given state. However, I'm not quite sure how that can be done in Python and most of the tutorials I have read, dabble into concepts but don't show an actual implementation in Python. Does anyone know how do/undo functionality work in Python? For reference, this is my (naive and probably ridden with errors) code: # command class DrawCommand: def __init__(self, draw, point1, point2): self.draw = draw self.point1 = point1 self.point2 = point2 def execute_drawing(self): self.draw.execute(self.point1, self.point2) def execute_undrawing(self): self.draw.unexecute(self.point1, self.point2) # invoker class InvokeDrawALine: def command(self, command): self.command = command def click_to_draw(self): self.command.execute_drawing() def undo(self): self.command.execute_undrawing() # receiver class DrawALine: def execute(self, point1, point2): print("Draw a line from {} to {}".format(point1, point2)) def unexecute(self, point1, point2): print("Erase a line from {} to {}".format(point1, point2)) instantiating as follows: invoke_draw = InvokeDrawALine() draw_a_line = DrawALine() draw_command = DrawCommand(draw_a_line, 1, 2) invoke_draw.command(draw_command) invoke_draw.click_to_draw() invoke_draw.undo() output: Draw a line from 1 to 2 Erase a line from 1 to 2 Obviously, this test doesn't allow stack several actions to undo. Maybe I'm completely mistaken so I would appreciate some help. A: How I'd go about this class Command(object): def execute(self, canvas): raise NotImplementedError class DrawLineCommand(Command): def __init__(self, point1, point2): self._point1 = point1 self._point2 = point2 def execute(self, canvas): canvas.draw_line(self._point1, self._point2) class DrawCircleCommand(Command): def __init__(self, point, radius): self._point = point self._radius = radius def execute(self, canvas): canvas.draw_circle(self._point, self._radius) class UndoHistory(object): def __init__(self, canvas): self._commands = [] self.canvas = canvas def command(self, command): self._commands.append(command) command.execute(self.canvas) def undo(self): self._commands.pop() # throw away last command self.canvas.clear() for command self._commands: command.execute(self.canvas) Some thoughts: * *Trying to undo an action can be hard. For example, how would you undraw a line? You'd need to recover what used to be under that line. A simpler approach is often to revert to a clean slate and then reapply all the commands. *Each command should be contained in a single object. It should store all of the data neccesary for the command. *In python you don't need to define the Command class. I do it to provide documentation for what methods I expect Command objects to implement. *You may eventually get speed issues reapplying all the command for an undo. Optimization is left as an excersize for the reader. A: Here is an implementation keeping the commands in a list. # command class DrawCommand: def __init__(self, draw, point1, point2): self.draw = draw self.point1 = point1 self.point2 = point2 def execute_drawing(self): self.draw.execute(self.point1, self.point2) # invoker class InvokeDrawLines: def __init__(self, data): self.commandlist = data def addcommand(self, command): self.commandlist.append(command) def draw(self): for cmd in self.commandlist: cmd.execute_drawing() def undocommand(self, command): self.commandlist.remove(command) # receiver class DrawALine: def execute(self, point1, point2): print("Draw a line from" , point1, point2)
{ "language": "en", "url": "https://stackoverflow.com/questions/7509129", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: logout not working in IPAD Really weird think happening with my site! I have a "welcome {{user.email}}" in the top of my base.html page! So far was working fine, but when I tested the site in a IPAD2 and Iphone4, I saw that, the login part wasnt working right!What I mean by that is, if I am logged in the welcome message has been showing, but if I logout, some pages are still showing the welcome message in the top, but if I reload the page then it works fine afterwards! It seems that JUST ipad is holding some kind of cache! is it that even possible? Just for record I am not using cache in my django app! my settings.py file has: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', } } So, I know that django is not messing things up! it is something with ipad!(client side) does someone have a clue about it?! EDIT I tried already adding; <META HTTP-EQUIV="Pragma" CONTENT="no-cache"> <META HTTP-EQUIV="Expires" CONTENT="-1"> and <meta http-equiv="Cache-control" content="no-cache"> no success so far though. EDIT2: This is happening in Safari also! but just in Safari and MAC os!! using Safari in windows works fine! A: you're probably holding it wrong... if you really think it's client side maybe you can try to add some meta tags for cache control and see if that helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509135", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Does this program end in an infinite loop? How can I tell? I run the program and all I see is white space below Netbeans. At first I thought it did not run then I ran four of the programs by accident and Netbeans crashed. So my first question: is it an infinite loop, and if so why? From what I can see it is int = 0, 0 is >=0 So it should run as 0 + 0... wait if int number and int sum are both zero then does that mean the program can't proceed because it is stuck with looping zeros? But why wouldn't it show the output of 0 many times instead of being blank? public static void main(String[] args) { int number = 0; int sum = 0; while (number >= 0 || number <= 10) { sum += number; number += 3; System.out.print(" Sum is " + sum); } } A: Think through the logic yourself. When will the number ever not be greater than or equal to 0? You know you have an or operator (||), and you know that it will be true if either statement on the right or left are true. Maybe you want to use a different operator there? Again think through the logic as it won't lie to you. In fact you should walk through your code with a pencil and paper starting with 0, and seeing what happens on paper as this will show you your error. A: Yes, it's an infinite loop, you probably meant: while (number >= 0 && number <= 10) Otherwise, the number will always be greater than or equal zero, and will always loop again. EDIT: The number >= 0 isn't even necessary. It will work with just: while (number <= 10) A: Yes it will be an infinite loop || means or while (a || b) { //do something } you only need to satisfy ANY ONE CONDITION (be it a, or b, or both) for the while loop to execute. As for why a bunch of whitespaces instead of a bunch of zeros, I have no idea. A: You step through it in the debugger!! It's worth learning how to use the debugger especially if you're not got at spotting bugs manually yet.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509136", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: SQL Server query optimisation I inherited this hellish query designed for pagination in SQL Server. It's only getting 25 records, but according to SQL Profiler, it does 8091 reads, 208 writes and takes 74 milliseconds. Would prefer it to be a bit faster. There is an index on the ORDER BY column deployDate. Anyone have any ideas on how to optimise it? SELECT TOP 25 textObjectPK, textObjectID, title, articleCredit, mediaCredit, commentingAllowed,deployDate, container, mediaID, mediaAlign, fileName AS fileName, fileName_wide AS fileName_wide, width AS width, height AS height,title AS mediaTitle, extension AS extension, embedCode AS embedCode, jsArgs as jsArgs, description as description, commentThreadID, totalRows = Count(*) OVER() FROM (SELECT ROW_NUMBER() OVER (ORDER BY textObjects.deployDate DESC) AS RowNumber, textObjects.textObjectPK, textObjects.textObjectID, textObjects.title, textObjects.commentingAllowed, textObjects.credit AS articleCredit, textObjects.deployDate, containers.container, containers.mediaID, containers.mediaAlign, media.fileName AS fileName, media.fileName_wide AS fileName_wide, media.width AS width, media.height AS height, media.credit AS mediaCredit, media.title AS mediaTitle, media.extension AS extension, mediaTypes.embedCode AS embedCode, media.jsArgs as jsArgs, media.description as description, commentThreadID, TotalRows = COUNT(*) OVER () FROM textObjects WITH (NOLOCK) INNER JOIN containers WITH (NOLOCK) ON containers.textObjectPK = textObjects.textObjectPK AND (containers.containerOrder = 0 or containers.containerOrder = 1) INNER JOIN LUTextObjectTextObjectGroup tog WITH (NOLOCK) ON textObjects.textObjectPK = tog.textObjectPK AND tog.textObjectGroupID in (3) LEFT OUTER JOIN media WITH (NOLOCK) ON containers.mediaID = media.mediaID LEFT OUTER JOIN mediaTypes WITH (NOLOCK) ON media.mediaTypeID = mediaTypes.mediaTypeID WHERE (((version = 1) AND (textObjects.textObjectTypeID in (6)) AND (DATEDIFF(minute, deployDate, GETDATE()) >= 0) AND (DATEDIFF(minute, expireDate, GETDATE()) <= 0)) OR ( (version = 1) AND (textObjects.textObjectTypeID in (6)) AND (DATEDIFF(minute, deployDate, GETDATE()) >= 0) AND (expireDate IS NULL))) AND deployEnglish = 1 ) tmpInlineView WHERE RowNumber >= 51 ORDER BY deployDate DESC A: I am in a similar position to with the same sort of queries. Here are some tips: * *Look at the query plans to make sure you have the right indexes. *I'm not sure if MSSQL optimizes around DATEDIFF(), but if it doesn't you can precompute threshold dates and turn it into a BETWEEN clause. *If you don't need to order by all those columns in your ROW_NUMBER() clause, get rid of them. That may allow you to do the pagination on a much simpler query, then just grab the extra data you need for the 25 rows you are returning. Also, rewrite the two LEFT OUTER JOINs like this: LEFT OUTER JOIN ( media WITH (NOLOCK) LEFT OUTER JOIN mediaTypes WITH (NOLOCK) ON media.mediaTypeID = mediaTypes.mediaTypeID ) ON containers.mediaID = media.mediaID which should make the query optimizer behave a little better.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509138", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I register for an event on an object without the need for an anonymous class? I'm creating an android app. I have a Dialog, and I want to handle the onCancel() event without using an anonymous class because it's cleaner and there are class variables I need access to from the main Activity class. I'm looking for a way to register for events on an object similar to .NET, where I can handle it in a separate method in the class without the need for an anonymous class. A: There is a nice example here in the Event Listeners section. The first example uses an anonymous class for the listener; the second uses a method inside the Activity. No extra class needed. TL;DR Here is the code stolen from that page: public class ExampleActivity extends Activity implements OnClickListener { protected void onCreate(Bundle savedValues) { ... Button button = (Button)findViewById(R.id.corky); button.setOnClickListener(this); } // Implement the OnClickListener callback public void onClick(View v) { // do something when the button is clicked } ... } You can modify this to use onCancel().
{ "language": "en", "url": "https://stackoverflow.com/questions/7509139", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PlaceRequest with parameters to Popup Presenter I trying to pass a parameter in the placerequest to a presenter that will be a popup, but, the i receive empty parameters in the popup presenter.. am i forgot anything? AddProjetoPresenter public class AddProjetoPresenter extends Presenter<AddProjetoPresenter.AddProjetoView, AddProjetoPresenter.AddProjetoProxy> { @ProxyCodeSplit @NameToken(NameTokens.addproj) public interface AddProjetoProxy extends ProxyPlace<AddProjetoPresenter> { } public interface AddProjetoView extends View { HasValue<String> getNome(); HasValue<Date> getDtInicio(); HasValue<Date> getDtFim(); HasClickHandlers getAddRequisitos(); HasClickHandlers getAddStakeholders(); HasClickHandlers getBtCancelar(); HasClickHandlers getBtSalvar(); } private final DispatchAsync dispatch; private final PlaceManager placeManager; private Projeto projeto; @Inject public AddProjetoPresenter(final EventBus eventBus, final AddProjetoView view, final AddProjetoProxy proxy, final DispatchAsync dispatch, final PlaceManager placeManager) { super(eventBus, view, proxy); this.dispatch = dispatch; this.placeManager = placeManager; } @Override protected void revealInParent() { RevealContentEvent.fire(this, MainPresenter.TYPE_SetMainContent, this); } @Override protected void onBind() { super.onBind(); getView().getBtSalvar().addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { } }); getView().getAddRequisitos().addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { PlaceRequest pr = new PlaceRequest(NameTokens.addreq); pr.with("oi", "oiiiii"); // HERE placeManager.revealPlace(pr, false); } }); } } AddRequisitoPresenter public class AddRequisitoPresenter extends Presenter<AddRequisitoPresenter.AddRequisitoView, AddRequisitoPresenter.AddRequisitoProxy> { @ProxyCodeSplit @NameToken(NameTokens.addreq) public interface AddRequisitoProxy extends ProxyPlace<AddRequisitoPresenter> { } public interface AddRequisitoView extends PopupView { DialogBox getDialog(); } private final DispatchAsync dispatcher; private Projeto projeto; @Inject public AddRequisitoPresenter(final EventBus eventBus, final AddRequisitoView view, final AddRequisitoProxy proxy, final DispatchAsync dispatcher) { super(eventBus, view, proxy); this.dispatcher = dispatcher; } @Override public void prepareFromRequest(PlaceRequest request) { super.prepareFromRequest(request); getView().getDialog().setText(request.getParameterNames().size() + ""); //SIZE IS ZERO!! } @Override protected void onBind() { super.onBind(); } @Override protected void revealInParent() { RevealRootPopupContentEvent.fire(this, this); } } I think ai doing something wrong... thanks in advance. A: From what I understood in the wiki, a popup can't be a place, and it needs a parent presenter. I see two obvious problems here : * *Your second presenter (the popup) should implement PresenterWidget, not Presenter *You can't display a popup by calling placeManager.revealPlace(), because a popup is not a place. Instead, you have to apply one of the two methods explained in the wiki (addToPopupSlot() or RevealRootPopupContentEvent.fire(), both called from the parent).
{ "language": "en", "url": "https://stackoverflow.com/questions/7509141", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I make a navigation bar's color any color I want? I created a navigation bar programmatically, and as far as I know, you can only make it "UIColor BlackColor" or "WhiteColor" or whatever. So the options are limited. Is there a way to be able to choose from a color palette or something, or use RGB sliders or some way to have thousands of color options? A: Sure. You can make an arbitrary UIColor like so: UIColor *theColor = [UIColor colorWithRed:0.5f green:0.75f blue:0.0f alpha:1.0f]; A: You can set the color by using the command: navigationController.navigationBar.tintColor = [UIColor colorWithRed: green: blue: ] Or the pre made colors in UIColor by typing: [UIColor blueColor]; "blue" being able to be replaced with many basic colors like black, red, grey, green, etc. But if you want an image as the background of the NavBar, you need to make a custom class that is a subclass of UINavigationBar.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509146", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Need help setting up simple Virtual Directory in IIS7 Noobie question... Using IIS7, I am trying to create a virtual directory for the folder that contains my video files, but can't get my head around how it is done. For example... The existing address is http://www.mydomain.com/members which points to C:\wwwroot\mydomain\members I need http://www.mydomain.com/flash-members to point to the same path. The existing IIS path to the members folder is Server\Sites\www_mydomain_com\members (has application icon) Any help is appreciated. A: For your example, assuming www_mydomain_com is the Site (little world icon), you can do this by: * *Open IIS Manager *Right-click the web site, select Add Virtual Directory *In the Alias field, enter flash-members *In the Physical Path field, enter your path (C:\wwwroot\mydomain\members)
{ "language": "en", "url": "https://stackoverflow.com/questions/7509147", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Import third partiy control to own assembly in c# I have a bunch of winform control libraries in my visual studio 2008 after I installed a third party. How can I import those controls to my own custom library? For example Instead of using ThirdPartyAssembly.ControlName I can use MyAssembly.CotrolName (all controls still have full functionality the same as the original) Can anyone please give me an example? A: You can not import thirdparty controls into your own library. You can only reference them. You can use namespace alias feature if want to reference these controls in code under a different name: using MyNamespace = ThirdPartyNamespace; ... var control = new MyNamespace.ControlName(); If you are dealing with two versions of the same thirdparty dll you can use extern alias. Read this or this: extern alias ThirdPartyAssemblyV1; extern alias ThirdPartyAssemblyV2; ... var v1 = new ThirdPartyAssemblyV1::Namespace.ControlName(); var v2 = new ThirdPartyAssemblyV2::Namespace.ControlName(); A: It's seem like not possible. You can reference it. But another way can do it, package two difference library as assembly's resource, reflection to call method after extract to disk.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509148", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Problems in php to add products in a shop cart I have these 3 classes: shopping cart->orders->products. First I add a product, when I add the second, I compare with other products in the array products in the object orders. if count($product)==0, then add the firs product if count>0, I compare the id´s of the products in the array with the new product I want to add : public function setProduct($product,$new_quantity){ if($this->num_product == 0) { $this->product[$this->num_product]=$product; $this->num_product++; } else if($this->num_product > 0) { for($i=0; $i < $this->num_product; $i++) { if($this->product[$i]->getIdproduct() == $product->getIdproduct()) { $this->product[$i]->setQuantity($this->product[$i]->getquantity()+$new_quantity); break; } else { continue; } $this->product[$this->num_product]=$product; $this->num_product++; } } } When I finish the comparison, I have to add these new product but this doesn't work. What is my mistake? A: Your method is really complicated for what you want to do. First of all, $this->num_product is exactly the same thing as count($this->product). So why use a variable to hold this information ? Second of all, no need to separate the case of zero products and some products in the cart, the for loop won't execute if there's no product in the cart. I propose this as a solution : public function setProduct($product,$new_quantity){ for($i=0; $i < count($this->product); $i++) { if($this->product[$i]->getIdproduct() == $product->getIdproduct()) { $this->product[$i]->setQuantity($this->product[$i]->getquantity() + $new_quantity); return; // we found our product, get out of the function. } } // the product was not found in the array, add it to the end $this->product[]=$product; } If you want to keep your code, I think the mistake is that you add the product to the array at each iteration of the loop (the last two lines of the loop, after the if clause), but it's really hard to say without some explanation about what you think is wrong. A: The problem in your code is that the last two lines of the the for loop will never get executed. If the if contidion is true it will break the loop, otherwise will continue without ever reaching these two lines. The easiest way is to use retun if your function doesn't do anything after the loop. public function setProduct($product,$new_quantity){ if($this->num_product == 0) { $this->product[$this->num_product]=$product; $this->num_product++; } else if($this->num_product > 0) { for($i=0; $i < $this->num_product; $i++) { if($this->product[$i]->getIdproduct() == $product->getIdproduct()) { $this->product[$i]->setQuantity($this->product[$i]->getquantity()+$new_quantity); return; } } $this->product[$this->num_product]=$product; $this->num_product++; } } See also what @krtek says about the need of no checking for 0 elements
{ "language": "en", "url": "https://stackoverflow.com/questions/7509150", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Changing table info with Rails migration In my original migration, I had this: create_table :credit_purchases do |t| t.column :amount, :decimal, :precision => 8, :scale => 2, :null => false t.column :time, :datetime, :null => false end Which produced the following MySQL table definition: CREATE TABLE `credit_purchases` ( `id` int(11) NOT NULL AUTO_INCREMENT, `amount` decimal(8,2) NOT NULL, `time` datetime NOT NULL, PRIMARY KEY (`id`), ) When I run this, it doesn't change the definition at all: change_column :credit_purchases, :amount, :decimal, :precision => 8, :scale => 2 change_column :credit_purchases, :time, :datetime I'd expect the definition result to be: CREATE TABLE `credit_purchases` ( `id` int(11) NOT NULL AUTO_INCREMENT, `amount` decimal(8,2) DEFAULT NULL, `time` datetime DEFAULT NULL, PRIMARY KEY (`id`), ) What do I have to do to produce the desired result? I want to avoid defining DB constraints via the migration. A: Try explicitly adding :null => true.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509151", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Catching SocketTimeOut error and responding I have an activity that will require jsoup to connect to a url. The problem is every now and again i will get 09-21 23:11:56.140: WARN/System.err(5725): java.net.SocketTimeoutException: Connection timed out 09-21 23:11:56.140: WARN/System.err(5725): at org.apache.harmony.luni.platform.OSNetworkSystem.connect(Native Method) 9-21 23:11:56.140: WARN/System.err(5725): at dalvik.system.BlockGuard$WrappedNetworkSystem.connect(BlockGuard.java:369) 09-21 23:11:56.140: WARN/System.err(5725): at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:208) 09-21 23:11:56.140: WARN/System.err(5725): at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:431) 09-21 23:11:56.140: WARN/System.err(5725): at java.net.Socket.connect(Socket.java:901) 09-21 23:11:56.140: WARN/System.err(5725): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:75) 09-21 23:11:56.140: WARN/System.err(5725): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:48) I want to figure out a way when this happens to keep trying until after lets say 3 tries. i was thinking catching the exception and then having for loop counter. I could use some implementation of this with some answers. Any suggestions? A: To confirm, you wish to perform a specific action that has the possibility of transient failure, returning an object when that action is successful? I've used the following pattern previously for this. public class RetryUtil { public static <T> tryAction(Callable<T> action, int maxTimes); } Implement it such that it returns the result of the Callable when that function succeeds and tries again (using a loop as you suggest) when it fails. You then define the repeatable action in an anonymous Callable and pass that in to tryAction.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509152", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ASP.NET displaying fixed DIV on top of page I'm using VS2010,C# to develop my ASP.NET web app, I'm going to insert a fixed header on top of my pages so that my content area has a smaller width and these fixed DIVs are always on top of my page, in this way contents should start displaying from bottom of DIVs and not from screen top, I'm not going to use master pages, what are my options? how should I arrange my page? thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/7509153", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UPDATED: cannot pass NSDictionary to UITableViewCell textlabel Updating this Thread as I have had some other help solving why I was not able to access the NSDictionarys values outside the method... I was initalizing it wrong thus autorelease was being called at the end of the method so when I was calling it outside of that method I was getting all sorts of errors.. So now basically I am trying to allocate the NSDictionarys values to the UITableViewCell Text inside cellForRowAtIndexPath however I am getting this error here is how I am trying to allocate it and the output at this point // Configure the cell... if(indexPath.row <= [self.sectionLetters count]){ // NSObject *key = [self.sectionLetters objectAtIndex:indexPath.row]; NSString *value = [self.arraysByLetter objectForKey:[self.sectionLetters objectAtIndex:indexPath.row]]; NSLog(@"thingy %@", value); cell.textLabel.text = value; } return cell; .output 2011-09-23 10:25:01.343 Code[6796:207] thingy ( Honda, Honda, Honda, Honda, Honda, Honda, Honda ) however, if I comment out //Cell.textLabel.text = value; I get this output .output2 2011-09-23 10:26:38.322 Code[6876:207] thingy ( Honda, Honda, Honda, Honda, Honda, Honda, Honda ) 2011-09-23 10:26:38.323 Code[6876:207] thingy ( Mazda, Mazda, Mitsubishi, Mitsubishi, Mitsubishi, Mitsubishi, Mitsubishi, Mitsubishi ) 2011-09-23 10:26:38.325 Code[6876:207] thingy ( Nissan, Nissan, Nissan, Nissan, Nissan, Nissan, Nissan ) 2011-09-23 10:26:38.326 Code[6876:207] thingy ( Toyota, Toyota, Toyota ) A: You know what, I think I know the problem so I'm going to make a guess. Because you're using arraysByLetter directly, I don't believe you're hitting the synthesized properties, but the backing variable instead. You need to use self.arraysByLetter (this will retain the Dictionary). At least, I've been using self.property forever, so I can't remember if this was a necessity or just a habit. Give that a shot.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509160", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iOS: How to ascertain the CPU type, e.g. A4 or A5, or instruction set architecture arm6 or arm7? Does Apple provide an API that gives access to this information? Does the ARM have an equivalent to the x86 CPUID instruction that I could use in an asm block? Thanks. A: Erica Sadun has written a number of useful queries. I would begin checking out the uidevice extensions code and see if you can find what you are looking for there. https://github.com/erica/uidevice-extension Also, as Gapton says, keep in mind that some device queries will not get App Store approval, especially the unpublished ones, but a fair number of them are okay to use. A: I need CPU model info and instruction set. So I try to do it as simple as possible: std::string GetCPUModel() { // you can compare results with https://www.theiphonewiki.com/wiki/List_of_iPhones struct utsname systemInfo; uname(&systemInfo); std::string version(systemInfo.version); size_t cpuModelPos = version.find("RELEASE_"); if (cpuModelPos != String::npos) { // for example: will return "ARM64_S8000" - for iPhone S6 plus return version.substr(cpuModelPos + strlen("RELEASE_")); } return {}; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7509167", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Which is the better way of validating user input, DB Constraints or Javascript? I want to validate user input on a Web Form, like valid numbers, date etc. Which one is the better way to validate, using Javascript functions or using Constraints in SQL Server? I want to reduce the code as much as possible and want to use most of the power of SQL Server itself. A: I would suggest both on the client side and on the server side, as potentially someone could have Javascript disabled and still be able to submit invalid content. I would suggest either writing constraints on your server side (in your actions) and then in your client side JS; alternatively you could look into ASP.Net MVC which allows you to write the validation in your model class (.cs) and then via an AJAX form the client side validations will be performed automatically. A: You must do both. Client-side validation to prevent all but sensible input, and server side (including in code prior to hitting the database), to prevent more malicious attempts at doing things. So, in ASP.NET, at the very least, use the built-in validator controls, which emit JavaScript if you want them to. Then, in server-side events that occur when, say, a submit button is clicked, check Page.IsValid to ensure the JavaScript was not bypassed. Next, ensure you are using parameterized queries to prevent SQL injection. And, lastly, always use constraints to ensure data correctness if all else fails. A: Both because : 1) if you allow the web form to pass invalid input, you are wasting bandwidth. Plus you have to prepare another page which says "oh you input something wrong please try again haha" 2) if you allow the DB to accept invalid input, its outright wrong because you risk corrupting the data (e.g. when javascript validation fails or missed something) A: Really this depends on what you are looking for. If you want something that is quick and very load load then using Javascript is the best way to go since there is no round trip to the server and wait times for the client. Downside is that Javascript can be disabled. This means you also have to have validation in your ASP. I wouldn't go with using constraints in the DB other than what is required for a relational database because that just makes your site break. A: The general rule when submitting data via web forms is that you must validate on the server side, and you may also validate client side. If by "SQL vs. JavaScript" you mean server vs. client, the SQL is imperative; the JavaScript is optional but in modern apps you validate to avoid roundtrips to the server. Note that you may perform server side validation outside the database but in many cases, as in your words, "leverag[ing] the power of SQL Server" is appropriate. A: I guess that it depends on whether or not you will be writing into the database from a different application. I am a big proponent of enforcing data restrictions at the database level, as well as the client application level, because you never know when you are going to need to write a random script to batch import data from a different source etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509168", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Twitter Equivalent to Facebook Comments? My site needs the Twitter equivalent of the Facebook Comments plugin... You may be aware of the fact that Twitter only searches back about a week, so comments would be lost just a few days after being made! Is there a service that would allow me to show the tweets that contain the given page's unique #hashtag? I'm looking to put together a system that searches for the hashtag and puts those tweets up for display, even if the tweets are old. Does anyone know how to make this possible? I'm not that good of a programmer, FYI... A: No. The Twitter Search API will not let you search that far back. The Search API is not complete index of all Tweets, but instead an index of recent Tweets. At the moment that index includes between 6-9 days of Tweets. You cannot use the Search API to find Tweets older than about a week. From https://dev.twitter.com/docs/using-search
{ "language": "en", "url": "https://stackoverflow.com/questions/7509180", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Caching data in hidden & dynamic tabs of tabview In my application, I have groups & the list of groups specific to a user are shown to him through a left column list, in a similar fashion as google groups(shown in image below). I want that as the user moves on with switching to different groups shown in the list, the front-end should cache the visited groups, so that next time user comes back to the same group there is no need to read again from the server. I am thinking of implementing this through dynamically adding hidden tabs to the jquery tabview whenever a new group is visited. Does this sounds like a good optimization ? Is this kind of optimization used on sites ? (I would be auto-updating the content of groups after every specified interval so that data shown in the group is most fresh and not just the cached one.) A: I'll give you a reason why you shouldn't do this and instead look at HTTP caching. Hopefully you're already a RESTafarian in that you use and understand the basic principles of REST and why HTTP is scalable. There's no need to invest in complex caching schemes with JavaScript if you make sure that your GETs are cached locally, and this is probably what you should be focusing on. By using the HTTP caching mechanism you can completely eliminate any server round-trips if you so please. Invalidation of cached data can be tricky but for general viewing purposes this is something which is pretty straight forward and it's going to give you really good performance (without increasing the complexity of your existing JavaScript, which I recon that's a good thing).
{ "language": "en", "url": "https://stackoverflow.com/questions/7509181", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I add bookmarks in Xcode 4? Can I add bookmarks at certain code lines in Xcode 4? I'm currently using breakpoints for this purpose, but when I add/delete some code before the positions of the breakpoints, they don't shift accordingly, and therefore no longer point to the original lines. I have to manually adjust them. That's too bad. A: You can use #pragma mark My Fancy Bookmark directly in your code and even #pragma mark - for a separation line. The bookmarks will appear under the title bar when you click on the name of the current function.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509183", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Using update in a firebird stored procedure but data not changing I have the following stored procedure. I found a bug in my code that had resulted in bad data. I wrote this procedure to fix the data. CREATE OR ALTER PROCEDURE RESET_DISABLED_COUNT returns ( person integer, game integer, disabled integer, cnt integer) as begin for select gr.person_id, gr.game_id, gr.disableds from game_roster gr into :person, :game, :disabled do begin select count(gr.id) from game_roster gr where gr.disabled_by_id = :person and gr.game_id = :game into cnt; if (cnt <> disabled) then begin update game_roster gr set gr.disableds = :cnt where (gr.person_id = :person) and (gr.game_id = :game); end end end I then run the procedure from IBExpert and commit. However, when I run a query on the table, it shows that the old data is still there. What am I missing? A: 1) Can Cnt and Disabled variables contain NULLs? If so, change condition for if (:cnt IS DISTINCT FROM :disabled) then ... 2) Make sure that you commit transaction after SP run. 3) Make sure that transaction you select data on is not SNAPSHOT transaction. If so, commit and reopen it before running SELECT query. 4) Recheck logic of your procedure. 5) Do you run your procedure inside IBExpert's debugger? A: If you are using C# and ado, this snippet will be handy. Works file on Firebird 1.5 the usp UPDATE_stuff was a typical update or insert type of proc you take for granted with MSSQL. This will allow you to use a stored procedure and actually save the data and save weeks of wasted time. Config.DB4FB.Open is just a nested class that opens a new FbConnection witt a optional connection string, cos if you are using firebird you need all the grief abstracted away:) FbTransaction FTransaction=null; using (FbConnection conn = Config.DB4FB.Open(ConnectionString)) { FbTransactionOptions options = new FbTransactionOptions(); options.TransactionBehavior = FbTransactionBehavior.NoWait; FTransaction = conn.BeginTransaction(options); FbCommand cmd = conn.CreateCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "UPDATE_stuff"; cmd.Parameters.AddWithValue("KEY", key); cmd.Transaction = FTransaction; FbDataReader reader = cmd.ExecuteReader() while (reader.Read()){} FTransaction.Commit(); } A: Do you need to return the 4 output variables you set? If you DONT need the return values, this is the same thing and "should" work CREATE PROCEDURE RESET_DISABLED_COUNT AS declare person integer; declare game integer; declare disabled integer; declare cnt integer; begin for select gr.person_id, gr.game_id, gr.disableds from game_roster gr into :person, :game, :disabled do begin select count(gr.id) from game_roster gr where gr.disabled_by_id = :person and gr.game_id = :game into cnt; if (cnt <> disabled) then begin update game_roster gr set gr.disableds = :cnt where (gr.person_id = :person) and (gr.game_id = :game); end end end
{ "language": "en", "url": "https://stackoverflow.com/questions/7509186", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android: Get and Open Email and remove Bluetooth i want to choice a app to send email:only email app to send my email,i have read How to open Email program via Intents (but only an Email program) i used intent.setType("message/rfc822") ,it very well,but Bluetooth and email give me to choice,i want to remove Bluetooth,and want to Leave only email.can you tell me how to send email not to show Bluetooth to give mo choice; edit: if i used Intent intent = new Intent(Intent.ACTION_SENDTO); the bluetooth is remove but add Text messages t0 give me choice.i also used Intent intent = new Intent(Intent.ACTION_VIEW); Uri data = Uri.parse("mailto:?subject=" + subject + "&body=" + body); intent.setData(data); startActivity(intent); the bluetooth also remove but also add add Text messages t0 give me choice.is there i way to only email app to send email?
{ "language": "en", "url": "https://stackoverflow.com/questions/7509194", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Custom UINavigation image disappears when app comes back from multi-tasking I have a category to display a custom image in an app's UINavigationBar. When the app comes back from the background the image sometimes disappears and all I am left with is a white navigation bar with buttons. The category I'm using is below, can anyone advise please? @implementation UINavigationBar (CustomImage) -(void)drawRect:(CGRect)rect { cardSmartAppDelegate *delegate = (cardSmartAppDelegate *)[[UIApplication sharedApplication] delegate]; [delegate.navImage drawInRect:rect]; } @end A: You shouldn't use a category to override a method. Sometimes it works, but often it doesn't. Rumor has it that it will quit working altogether soon. See my code in this item for how to do what you want: Custom UINavigationBar Background
{ "language": "en", "url": "https://stackoverflow.com/questions/7509195", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hibernate first start Make application slow I use Hibernate for my desktop swing applications.The first database access makes the application slow,not responding.I think it is because the hibernate's libraries takes time to load.This problem occurs specially at the loging.it takes time to go from loging page to home page(It makes the user unpleasant). Any one tell me how to avoid this slowness please. A: The slow part of Hibernate is buliding the SessionFactory. Make sure you only do it once, and get it done before the user needs to interact with the database. Your problem should go away then. A: This article is about NHibernate but it might be worth trying: * *merging hbm files into one *initializing session factory on a background thread *have two session factories, one as fast 'initialization' session that only contains entities needed during initialization and put the rest entities into another
{ "language": "en", "url": "https://stackoverflow.com/questions/7509198", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: can not active click event after animation of the view this is the structure of my view linearlayout orientate = horizontal listview1 listview2 listview3 and I set listview1.start(animation) but, after animation the click event can not work.but it will effect on its origin position. I also animation.setFillAfter(true) animation.setFillEnable(true). And, what's more I use the delegate to move the effective position. but failed. for(int i = 0; i<mViews.size();i++){ mViews.get(i).startAnimation(moveLeftAnimation); Rect rect = new Rect(); mViews.get(i).getHitRect(rect); rect.left -= 413; rect.right -= 413; Log.e("filebrowser view move left", "rect left = "+rect.left +" right = "+rect.right); setTouchDelegate(new TouchDelegate(rect, mViews.get(i))); } mViews is a arraylist, which stores listview1 listview2 listview3.Can anyone help me.thanks for any help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509206", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to break out of the loop only if a certain case is met, but then continue the iteration? I realize that the title may be somewhat confusing, so I apologize. Basically, this is my code: while i < 5: do stuff if i == 3: print "i is 3" break Now all that sounds pretty simple, right? Except I don't really want to BREAK from the loop as much as I'd want it to start over again. So in this case the desired result would be to iterate through 1, 2, then when 3 break out, but then continue iterating with 4. How do I do that? A: Instead of break use continue Now, I pretty much never use continue as I find it is usually clearer to rework the code to avoid it. Of course that's really easy in this example, if you have trouble with a more complex example ask about that one. A: while i < 5: do stuff if i == 3: print "i is 3" continue
{ "language": "en", "url": "https://stackoverflow.com/questions/7509211", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: LINQ: When to use Compiled Queries? I'd like some expert advice on this. I've used compiled queries before, but for this particular case, i'm not sure whether it's appropriate. It's a search form where the query changes and is dependent on what is being searched on. static Func<DBContext, int, IQueryable<Foo>> Search = CompiledQuery.Compile( (DBContext db, int ID) => db.Person .Where(w => w.LocationID = ID) .Select(s => new Foo { Name = s.PersonName, Age = s.Age, Location = s.LocationName, Kin = s.Kin })); Now if someone fills in the search box, i want to extend the query by adding another Where statement to the query: var query = Search(context, 123); query = query.Where(w => w.Name.Contains(searchString)); So my question is, is it returning all the results where LocationID == 123, then checking the results for a searchString match? Or is it actually extending the compiled query? If it's the former (which i suspect it is), should scrap the CompiledQuery and just create a method that extends the query then return it as a list? Also, what are the best practices for CompiledQuery usage and is there a guideline of when they should be used? Note: I'm using the above in an ASP.NET website with Linq to SQL. Not sure if that makes any difference. Thanks A: The problem is that the compiled query is set in stone; it knows what SQL it will run against the database. The lambda expression is lazy loaded however, and cannot modify the compile query as it is being run during run time. The bad news is that it will return all of the records from the database, but it will query those records in memory to further refine them. If you want to compile the query then I would suggest writing two queries with different signatures. A: As far as I know, it is good practice to compile your query once, that is the whole point of pre-compiled query(and that's why your pre-compiled query is static), it saves time to compile that query into SQL. If it extend that pre-compiled query, then it is compiling that query again, which you loose gains. Query result on result (your query variable) is no longer LINQ to SQL. A: Just include your additional condition in your compiled query. DB.Person.Where(w => w.LocationID == ID & (searchString=="" || w.Name.Contains(searchString))) A: If i am right then you need some dynamic where clause in linq. So for that i would suggest go this way IEnumerable list; if(condition1) { list = Linq Statement; } if(condition2) { list = from f in list where con1=con && con2=con select f; } if(condition3) { list = from n in list con1=con && con2=con select f; } I hope you got my words.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509217", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Weighted win percentage by number of games played Im looking to create a ranking system for users on a gaming site. The system should be based of a weighted win percentage with the weighted element being the number of games played. For instance: 55 wins and 2 losses = 96% win percentage 1 win and 0 losses = 100% win percentage The first record should rank higher because they have a higher number of wins. I'm sure the math is super simple, I just can't wrap my head around it. Can anyone help? A: ELO is more thorough because it considers opponent strength when scoring a win or loss, but if opponents are randomly matched a simple and very effect approach is: (Wins + constant * Average Win % of all players) / (Wins + Losses + constant) so with 0 games the formula is the average for all players, as you increase the number of games played the formula converges on the actual record. The constant determines how quickly it does this and you can probably get away with choosing something between 5 and 20. A: Yes, it is "super simple": Percentage = Wins * 100.0 / (Wins + Losses) To round to an integer you usually use round or Math.round (but you didn't specify a programming language). The value could be weighted on the number of wins, using the given ratio: Rank = Wins * Wins / (Wins + Losses) But there are other systems that understand the problem better, like Elo (see my comment). A: Another possibility would be my answer to How should I order these “helpful” scores?. Basically, use the number of wins to determine the range of likely possibilities for the probability that the player win a game, then take the lower end. This makes 55-2 beat 1-0 for any reasonable choice of the confidence level. (Lacking a reason to do otherwise, I'd suggest setting that to 50% -- see the post for the details, which are actually very simple.) As a small technical aside: I've seen some suggestions to use the Wald interval rather than Agresti-Coull. Practically, they give the same results for large inputs. But there are good reasons to prefer Agresti-Coull if the number of games might be small. (By the way, I came up with this idea on my own—though surely I was not the first—and only later found that it was somewhat standard.) A: How about score = (points per win) * (number of wins) + (points per loss) * (number of losses), where points per win is some positive number and points per loss is some negative number, chosen to work well for you application.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509219", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Removing/renaming files in python I am trying to figure out how I could remove certain words from a file name. So if my file name was lolipop-three-fun-sand,i would input three and fun in and they would get removed. Renaming the file to lolipop--sand. Any ideas on how to start this? A: Use string.replace() to remove the words from the filename. Then call os.rename() to perform the rename. newfilename = filename.replace('three', '').replace('fun', '') os.rename(filename, newfilename) A: import os line = 'lolipop-three-fun-sand' delete_list = raw_input("enter ur words to be removed : write them in single quote separated by a comma") for word in delete_list: line = line.replace(word, "") print line
{ "language": "en", "url": "https://stackoverflow.com/questions/7509221", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why is my mux not producing an output in Verilog? I've written what I thought would be a working MUX, but my output is stubbornly staying at high-impedance. Can someone please provide me with guidance? module mux_in #(parameter WIDTH = 1, parameter LOG_CHOICES = 1) ( input [LOG_CHOICES - 1 : 0] choice, input [(1 << LOG_CHOICES) * WIDTH - 1 : 0] data_i, output [WIDTH - 1 : 0] data_o ); assign data_o = data_i[WIDTH * choice + WIDTH - 1 : WIDTH * choice]; endmodule Here's my (bad) output: data_i: 11111010101111100001001100100010 data_o: zzzzzzzz Choice 0: (Expected 34) Output: z Choice 1: (Expected 19) Output: z Choice 2: (Expected 190) Output: z Choice 3: (Expected 250) Output: z A: This should not compile because the range expression is not constant. assign data_o = data_i[WIDTH * choice + WIDTH - 1 : WIDTH * choice]; Try this instead. assign data_o = data_i[WIDTH * choice + WIDTH - 1 -: WIDTH];
{ "language": "en", "url": "https://stackoverflow.com/questions/7509227", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using modulus in for loop I am trying to understand how to repeat loops using the mod operator. If you have two strings, "abc" and "defgh", how can % be used to loop through abc, repeating it until the end of defgh is reached? Namely, what is the mod relationship of the length of abc and defgh? I don't really understand this concept. A: Simple. std::string abc("abc"); std::string defgh("defgh"); for (size_t i = 0; i < defgh.length(); ++i) { printf("%c", abc[i % abc.length()]); } Think about what the Modulus operator is doing, it discretely divides the left hand side by the right hand side, and spits back the integer remainder. Example: 0 % 3 == 0 1 % 3 == 1 2 % 3 == 2 3 % 3 == 0 4 % 3 == 1 In our case, the left hand side represents the i'th position in "defgh", the right hand represents the length of "abc", and the result the looping index inside "abc". A: The typical usage of mod is for generating values inside a fixed range. In this case, you want values that are between 0 and strlen("abc")-1 so that you don't access a position outside "abc". The general concept you need to keep in mind is that x % N will always return a value between 0 and N-1. In this particular case, we also take advantage of the fact that if you increase x by 1 x % N also increases by 1. See it? Another important property of modulus that we use here is the fact that it "rolls over". As you increase x by 1, x % N increases by 1. When it hits N-1, the next value will be 0, and so on. Look at @Daniel's code. It's C++ but the concept is language-agnostic
{ "language": "en", "url": "https://stackoverflow.com/questions/7509228", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: change schema from indexed field to stored field without re-index in Solr We want to change schema from indexed field to stored field, for example orig one : <field name="cat" type="string" indexed="true" stored="false"> new one: <field name="cat" type="string" indexed="false" stored="true"> The tool or commands to help to achieve this without re-index all the documents? A: If you change your schema you have to re-index your documents. You could use multiple cores to avoid a restart of the servlet container, see Core RELOAD but you do need to re-index. A: This is not possible. When field is not stored, you have no option to fetch content for this field from index. A: Yes... you really can't do that, you must have to re-index. But re-index cannot be a problem, if you have a lot of docs you can use one of the SOLR imports or if you have a slave solr that is replicating with a master, you can stop the replication, re-index in master, and start the replication again. re-index is boring right? ^^
{ "language": "en", "url": "https://stackoverflow.com/questions/7509229", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Special box -activated when clicked, deactivated when clicked another places I wonder how can i do div box, which when it is clicked then something will happen to the time when we click in some other place. Notice that when we click more than one time in our box nothing special will heppen. A: $('#theDiv').one('click', function(){ $('#theOtherDiv').click(function(){ alert('I was clicked!'); }); }); http://jsfiddle.net/cpc9s/ A: you can keep a variable to detect whether mouse is inside or in outside, var isIn = false; $(document).ready(function() { $('#yourDiv').hover(function(){ isIn =true; }, function(){ isIn =false; }); $("body").mouseup(function(){ if(isIn) { //do your work }else{ //do your work } }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7509230", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Multiple AudioTracks, Single Thread or Multiple? In my application, I will be creating multiple Audio Tracks, some of which will need to play simultaneously. I'm going to use MODE_STREAM and write data in as the app runs. Sounds are going to be dynamically generated, which is why I use Audio Track as opposed to anything else. I have 4 options, I believe: * *AsyncTask *One UI thread and one thread that manages all the AudioTrack playing *One UI thread and one thread for each AudioTrack *One UI thread and a Thread Pool Which of the four methods would be the best way to manage multiple AudioTracks? I think Thread Pool is the way to go, but I'm not positive as I haven't actually used it. Any advice would be greatly appreciated A: For simplicity, I was just creating a new thread every time I played an AudioTrack. But, regardless it really doesn't matter. I found that when trying to play more than one AudioTrack at a time, there's a crackling/choppy sound. I believe this is just an issue with the Android system, not with my app. As of API level 9 (gingerbread) I can apply a session id to an audio track, which I believe would let me play it with SoundPool, which should make the playing of multiple AudioTracks at once much smoother. Right now, due to how many users are still on 2.2 and the fact that I don't have a gingerbread device, I will put this project aside until later. A: I think your best bet for this would be AsyncTask. A: Create an AsyncTask for every AudioTrack, and execute them with an Excecutor (on my Android 4.4, only the first task will be executed, if no Excecutor is used). Here is an example of streaming a microphone signal to AudioTrack and a audio file stream to an other AudioTrack in parallel. /** Task for streaming file recording to speaker. */ private class PlayerTask extends AsyncTask<Null, Null, Null> { private short[] buffer; private int bufferSize; private final AudioTrack audioTrack; ... @Override protected Null doInBackground(final Null... params) { ... while (!isCancelled()) { audioTrack.write(buffer, 0, bufferSize); } ... } } /** Task for streaming microphone to speaker. */ private class MicTask extends AsyncTask<Null, Null, Null> { private short[] buffer; private int bufferSize; private final AudioTrack audioTrack; ... @Override protected Null doInBackground(final Null... params) { ... while (!isCancelled()) { audioTrack.write(buffer, 0, bufferSize); } ... } } /** On the UI-thread starting both tasks in parallel to hear both sources on the speaker. **/ PlayerTask playerTask = new PlayerTask(); playerTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new Null()); MicTask micTask = new MicTask(); micTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new Null());
{ "language": "en", "url": "https://stackoverflow.com/questions/7509232", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: I have two R generated classes. How do I fix? I originally had my app all in one project. I decided to rearrange things so I could have multiple projects referencing the same code, so I moved a package to a plain java library, and some others to an android library. The main app originally had two packages; com.stuff // standard java stuff com.stuff.android // android specific stuff When I rearranged, I moved all the com.stuff package to the plain java project and some of the com.stuff.android classes to an android library. The main app now references both. Now my main app is generating two R classes! One in com.stuff and one in com.stuff.android. The android library has it's own R in com.stuff.android. Neither the android library or app have classes in com.stuff anymore. Only the plain java package has com.stuff package classes. Both R classes seem to have the same stuff, most of the time. But sometimes weird things happen, and I need to clean all the projects and rebuild to get it to work again, and it's just annoying. Why is it doing this? How do I fix it? I am also using subclipse, so maybe it's interfering somehow with all the refactoring A: Aha! Found it myself... how come articulating the problem seems to spur new ideas on where to look. * *The manifest of the application still had package="com.stuff" instead of com.stuff.android *Some of the layouts still had a namespace reference to com.stuff. Fixing those two solved the issue. Edit: And then I thought about this: Changing the package name of an upgraded Android application Oops.... so looked into my android library, and it was using com.stuff.android in the manifest... So I guess the app was trying to use both? Changed everything back to com.stuff, and now I have one R in com.stuff. Phew!
{ "language": "en", "url": "https://stackoverflow.com/questions/7509237", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: vertical menu in css not formatting correctly I am trying to show the menu as follows | HOME | | GAMES | | PLAYERS| |SCHEDULE| The problem is that my menu is showing like this | HOME || GAMES | |PLAYERS||SCHEDULE| and also.. how can I set the width of it to be consistent?, right now it takes only the length of the word inside of |HOME| but i would like to set this to a fix number.. I am new to css please help .#tabshor { width:100%; font-size:50%; line-height:5px; } #tabshor ul { margin:-30px; padding:150px 0px 0px 0px; line-height:10px; } #tabshor li { display:block; margin:0; padding:5; } #tabshor a { float:left; background:url("../images/tableft.gif") no-repeat left top; margin:0; padding:0 0 0 3px; text-decoration:none; } #tabshor a span { float:left; display:block; background:url("../images/tabright.gif") no-repeat right top; padding:10px 20px 20px 10px; color:#FFF; } #tabshor a span {float:none;} #tabshor a:hover span { color:#FFF; } #tabshor a:hover{ background-position:0% -42px; } #tabshor a:hover span { background-position:100% -42px; } div#tabshor>ul>li { display:block; position:relative; float:left; list-style:none; left:50px; } div#tabshor>ul>li ul{ position:absolute; display:none; list-style:none; left:100px; } div#tabshor>ul>li>a{ display:block; } div#tabshor>ul>li:hover ul{ display:block; z-index:500; width:50%; margin:10px 0px 0px -20px; width:100%; } div#tabshor ul li ul a{ display:block; width: 50px; } div#tabshor ul li a:hover{ background:red; font-style: oblique; } HERE IS THE HTML <div id="left_banner" class="divleftside"> <div id="tabshor"> <ul> <li><a href="index.html"><span>HOME</span></a></li> <li><a href="#"><span>GAMES</span></a></li> <li><a href="#"><span>PLAYERS</span></a> <ul> <li><a href="PLAYEERS.html"><span>PLAYERS</span></a></li> <li><a href="#"><span>SOCCER</span></a></li> <li><a href="#"><span>BASKETBALL</span></a></li> </ul> </li> <li><a href="#"><span>COURTS</span></a></li> <li><a href="#"><span>REFEREES</span></a></li> <li><a href="#"><span>ABOUT US</span></a></li> <li><a href="#"><span>CONTACT US</span></a></li> <li><a href="#"><span>REGISTER</span></a></li> </ul> </div> </div> A: Try: * *Remove float: left from div#tabshor>ul>li *Remove float: left from #tabshor a *Add width: 170px; to div#tabshor>ul>li>a Cleaning up your CSS might lead to less headaches. Also starting with an example like this vertical rollover list or this nested vertical rollover list might be easier.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509238", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: getting day value of last 7day from sqllite even if there is no record in database i need some help in getting the day value of last 7 days from SQLite. i currently able to get day value from the SQLite if there is a records. wat i need is to show the last 7 days if the guy did something. example, if the guys only drink a beer today, it will show drink - thur no - wed no - tue no - mon no - sun no - sat no - sat example if the guys did not drink anything, it will show no - thur no - wed no - tue no - mon no - sun no - sat no - sat example if the guys drink anything during the last 7 days, it will show no - thur drink - wed no - tue no - mon drink - sun no - sat no - sat this is the SQL code + (void) getInitialDataToDisplay:(NSString *)dbPath { DrinkTabsAndNavAppDelegate *appDelegate = (DrinkTabsAndNavAppDelegate *)[[UIApplication sharedApplication] delegate]; if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) { const char *sql = "SELECT DATE(datetime) FROM consumed GROUP BY DATE(datetime) ORDER BY datetime DESC"; sqlite3_stmt *selectstmt; if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) { while(sqlite3_step(selectstmt) == SQLITE_ROW) { NSString *dateDrunk = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 0)]; NSDate *theDate = [NSDate dateFromString:dateDrunk withFormat:@"yyyy-MM-dd"]; DayOfDrinks *drinkDayObj = [[DayOfDrinks alloc] initWithDateConsumed:theDate]; [drinkDayObj hydrateDetailViewData]; //NSLog([NSDate stringFromDate:drinkDayObj.dateConsumed withFormat:@"yyyy-MM-dd"]); [appDelegate.drinksOnDayArray addObject:drinkDayObj]; [drinkDayObj release]; } } } else sqlite3_close(database); //Even though the open call failed, close the database connection to release all the memory. } DrinkHistoryTableViewController.m if (drunked<7) { for (int i=drunked; i<7; i++) { NSString * dayString= [NSString stringWithFormat:@"Nil"];/ [dayArray addObject:dayString]; } } for(int i=drunked; i>0; i--) { DayOfDrinks *drinksOnDay = [appDelegate.drinksOnDayArray objectAtIndex:i-1]; NSString * dayString= [NSDate stringForDisplayFromDateForChart:drinksOnDay.dateConsumed]; [dayArray addObject:dayString];//X label for graph the day of drink. drinksOnDay.isDetailViewHydrated = NO; [drinksOnDay hydrateDetailViewData]; NSNumber *sdNumber = drinksOnDay.standardDrinks; // pass value over to Standard Drink Numbers //[sdArray addObject: sdNumber]; float floatNum = [sdNumber floatValue]; // convert sdNumber to foat [sdArray addObject:[NSNumber numberWithFloat:floatNum]];//add float Value to sdArray } can anybody help to answer my question thanks a lot. Des A: Update your query with this and try out : "SELECT DATE(datetime) FROM consumed GROUP BY DATE(datetime) ORDER BY datetime DESC Limit 7" You will get last 7 days information. A: Is that Objective C? Yuk. Too much code for a 'sqlite' question :] When working with reporting databases, datamining etc. it's not ridiculous to have a table with just dates in it that you can join with. You could have a table with just dates that are added to daily or whatever that you join across to and that would easily allow you to get YES or NO on whether they drank that day. (This would be a pretty lazy solution, but would work) The other option is to just query out the days they drank in the last 7 days... which may be 1 or 2 days. Then in code loop through today to today - 7 ... and then an inner loop to loop through your returned records to see if there is a match for that day. If there is, then you know they drank or did not drink. Nested loop would work, and should perform fine just doing it over 7 days. Those are 2 of plenty of options to solve it. I however loathe Objective C and have on interest in writing any tonight :]
{ "language": "en", "url": "https://stackoverflow.com/questions/7509241", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Recognizing route with regex? Let's say that I have a postback url that comes in as http://domain/merkin_postback.cgi?id=987654321&new=25&total=1000&uid=3040&oid=123 and other times as: http://domain/merkin_postback.php?id=987654321&new=25&total=1000&uid=3040&oid=123 If my route definition is map.purchase '/merkin_postback', :controller => 'credit_purchases', :action => 'create' it barks that either of the two forms above is invalid. Should I be using regex to recognize either of the two forms? A: This isn't a routing issue, it's a content format issue. You should be using respond_to. class CreditPurchasesController < ActionController::Base # This is a list of all possible formats this controller might expect # We need php and cgi, and I'm guesses html for your other methods respond_to :html, :php, :cgi def create # ... # Do some stuff # ... # This is how you can decide what to render based on the format respond_to do |format| # This means if the format is php or cgi, then do the render format.any(:php, :cgi) { render :something } # Note that if you only have one format for a particular render action, you can do: # format.php { render :something } # The "format.any" is only for multiple formats rendering the exact same thing, like your case end end end
{ "language": "en", "url": "https://stackoverflow.com/questions/7509242", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: About java Runtime self-written public API compatibility I just encounter a real problem about changed API. And i want to know more about this topic. Using the following example as a demo. There are 4 simple classes, Child class extends Parent. PubAPI is the class which provides public method for cient use. Client class invokes PubAPI's public methods. public class Parent { } public class Child extends Parent { } public class PubAPI { public Parent getChild(){ return new Child(); } } public class Client { public static void main(String[] args) { System.out.println(new PubAPI().getChild()); } } The first 3 class is provided by an API maker, let's say the above version is version 1. in Version 2, the PubAPI class is changed to return child type : public class PubAPI { public Child getChild(){ return new Child(); } } the 3 API provider class is in versoin 2 now, while if we don't recompile the "Client" class and use its version 1 generated class file. IT will fail in java runtime with error can not find the version 1 method (because the return type changes). I don't know this before, and i want to know if anyone know more about this topic , for example, if the public API add a throw, or addd a synchronize or the class become final, etc. In these situation, how will it hehave. IN all, what is the public API/class bytecode level compabability rule for API classes used by others. thanks. A: EDIT: You asked almost the exact same question two weeks back and accepted an answer. I am wondering what prompted you to ask again, you didn't think the rules would have changed in two weeks, did you? You are on the right track with the keyword bytecode level compatibility. It is called binary compatibility which you can look up on the net. For example, here The rules are not always easy to understand at first but usually make sense when you get an error and think about them. Best thing is to try the individual cases you have listed and when you get an error confirm in JLS that is an incompatibility and then try and rationalize for yourself why it is so. This question on so seems to discuss the exact same issue. The document at eclipse it sites is an easier read than JLS.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509244", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How is this memoized DP table too slow for SPOJ? SPOILERS: I'm working on http://www.spoj.pl/problems/KNAPSACK/ so don't peek if you don't want a possible solution spoiled for you. The boilerplate: import Data.Sequence (index, fromList) import Data.MemoCombinators (memo2, integral) main = interact knapsackStr knapsackStr :: String -> String knapsackStr str = show $ knapsack items capacity numItems where [capacity, numItems] = map read . words $ head ls ls = lines str items = map (makeItem . words) $ take numItems $ tail ls Some types and helpers to set the stage: type Item = (Weight, Value) type Weight = Int type Value = Int weight :: Item -> Weight weight = fst value :: Item -> Value value = snd makeItem :: [String] -> Item makeItem [w, v] = (read w, read v) And the primary function: knapsack :: [Item] -> Weight -> Int -> Value knapsack itemsList = go where go = memo2 integral integral knapsack' items = fromList $ (0,0):itemsList knapsack' 0 _ = 0 knapsack' _ 0 = 0 knapsack' w i | wi > w = exclude | otherwise = max exclude include where wi = weight item vi = value item item = items `index` i exclude = go w (i-1) include = go (w-wi) (i-1) + vi And this code works; I've tried plugging in the SPOJ sample test case and it produces the correct result. But when I submit this solution to SPOJ (instead of importing Luke Palmer's MemoCombinators, I simply copy and paste the necessary parts into the submitted source), it exceeds the time limit. =/ I don't understand why; I asked earlier about an efficient way to perform 0-1 knapsack, and I'm fairly convinced that this is about as fast as it gets: a memoized function that will only recursively calculate the sub-entries that it absolutely needs in order to produce the correct result. Did I mess up the memoization somehow? Is there a slow point in this code that I am missing? Is SPOJ just biased against Haskell? I even put {-# OPTIONS_GHC -O2 #-} at the top of the submission, but alas, it didn't help. I have tried a similar solution that uses a 2D array of Sequences, but it was also rejected as too slow. A: There's one major problem which really slows this down. It's too polymorphic. Type-specialized versions of functions can be much faster than polymorphic varieties, and for whatever reason GHC isn't inlining this code to the point where it can determine the exact types in use. When I change the definition of integral to: integral :: Memo Int integral = wrap id id bits I get an approximately 5-fold speedup; I think it's fast enough to be accepted on SPOJ. This is still significantly slower than gorlum0's solution however. I suspect the reason is because he's using arrays and you use a custom trie type. Using a trie will take much more memory and also make lookups slower due to extra indirections, cache misses, etc. You might be able to make up a lot of the difference if you strictify and unbox fields in IntMap, but I'm not sure that's possible. Trying to strictify fields in BitTrie creates runtime crashes for me. Pure haskell memoizing code can be good, but I don't think it's as fast as doing unsafe things (at least under the hood). You might apply Lennart Augustsson's technique to see if it fares better at memoization. A: The one thing that slows down Haskell is IO, The String type in Haskell gives UTF8 support which we don't need for SPOJ. ByteStrings are blazing fast so you might want to consider using them instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509245", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: photo gallery using Composite c1 cms I just started using composite C1 CMS. And I have built one sample site where I need to build the photo gallery. I was able to upload single single picture but confused to create gallery. I also need to upload multiple pictures one at a time. So,I will be very thankful to the solution A: Upload multiple files You can upload multiple pictures using the "Upload Multiple" command instead of the "Upload File" command in the media archive. Here is how to: * *On your computer select all the images you with to upload and make a ZIP file with them *In the C1 Console, on the Media perspective, execute the "Upload Multiple" command on the desired folder *In the dialog, browse to the ZIP from step 1 and upload. UPDATE: This is now documented at http://users.composite.net/C1/Image-Media/Upload-Multiple-Files.aspx Getting an Image Gallery There are pre-build galleries you can use. Consider using one of those rather than building your own. Here is a guide on adding a blog and gallery to Composite. The gallery used here uses Picasa (an online service for picture storage). If you want to upload your pictures to the CMS instead, install one of these packages: * *Composite.Media.ImageGallery.ADGallery *Composite.Media.NivoSlider *Composite.Media.ImageGallery.Slimbox2 They are all available as C1 Packages you can install, evaluate and uninstall if you dislike them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509247", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Get stream from absolute Uri I'm working with Windows Phone 7 and I have a very difficult problem. Please help me ! I want to get a stream form an absolute uri (from web) of a png image. But GetResourceStream method work only with relative uri. Then I found imagetool form http://imagetools.codeplex.com/ but to now my problem is not still solved. Could anyone give me a solution ? A: How about using HttpWebRequest and HttpWebResponse? var uri = new Uri("http://chriskoenig.net/wp-content/uploads/2011/04/givecamp_125125_ad.jpg", UriKind.Absolute); HttpWebRequest request = HttpWebRequest.Create(uri) as HttpWebRequest; request.BeginGetResponse((ar) => { var response = request.EndGetResponse(ar); Dispatcher.BeginInvoke(() => { using (var stream = response.GetResponseStream()) { var image = new BitmapImage(); image.SetSource(stream); MyImage.Source = image; } }); }, null); A: Try this one, BitmaiImage bmp=new BitmaiImage(); Image image=new Image(); Uri url = new Uri("http://Ur url", UriKind.Absolute); HttpWebRequest reqest = (HttpWebRequest)WebRequest.Create(url); reqest.BeginGetResponse(DownloadImageCallback, reqest); void DownloadImageCallback(IAsyncResult result) { HttpWebRequest req = (HttpWebRequest)result.AsyncState; HttpWebResponse responce = (HttpWebResponse)req.EndGetResponse(result); Stream s = responce.GetResponseStream(); Deployment.Current.Dispatcher.BeginInvoke(() => { bmp.SetSource(s); image.Source=bmp; }); } A: Try this simple Code Image stream from Absolute url and store to isolated storage namespace eQuadrigaWP7 { public class ItemViewModel : INotifyPropertyChanged { private string _imgURL; public string imgURL { get { return _imgURL; } set { if (value != _imgURL) { _imgURL = value; } } } private BitmapImage _Image; public BitmapImage Iimage { get { return _Image; } set { if (value != _Image) { _Image = value; } } } public void LoadIimage() { if (this.imgURL == null) throw new Exception("Error equadriga log"); HttpWebRequest downloadthumbnailrequest = (HttpWebRequest)WebRequest.Create(new Uri(this._imgURL)); ///this is main DownloadThumbNailState thumbnailState = new DownloadThumbNailState(); thumbnailState.AsyncRequest = downloadthumbnailrequest; downloadthumbnailrequest.BeginGetResponse(new AsyncCallback(HandleThumNailDownLoadResponse), thumbnailState); } private void HandleThumNailDownLoadResponse(IAsyncResult asyncResult) { DownloadThumbNailState thumbnailState = (DownloadThumbNailState)asyncResult.AsyncState; HttpWebRequest downloadthumbnailrequest = (HttpWebRequest)thumbnailState.AsyncRequest; thumbnailState.AsyncResponse = (HttpWebResponse)downloadthumbnailrequest.EndGetResponse(asyncResult); Stream imageStream = thumbnailState.AsyncResponse.GetResponseStream(); byte[] b = new byte[imageStream.Length]; imageStream.Read(b,0,Convert.ToInt32(imageStream.Length)); imageStream.Close(); MemoryStream ms = new MemoryStream(b); Deployment.Current.Dispatcher.BeginInvoke(() => { BitmapImage bmp = new BitmapImage(); bmp.SetSource(ms); String tempJPEG = "logo.jpg"; using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) { if (myIsolatedStorage.FileExists(tempJPEG)) { myIsolatedStorage.DeleteFile(tempJPEG); } IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(tempJPEG); WriteableBitmap wb = new WriteableBitmap(bmp); Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85); fileStream.Close(); this.Iimage = bmp; } }); } public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(String propertyName) { if (null != PropertyChanged) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } public class DownloadThumbNailState { public HttpWebRequest AsyncRequest { get; set; } public HttpWebResponse AsyncResponse { get; set; } } } } ItemViewModel imageitem = new ItemViewModel(); imageitem.imgURL = "http://www.yoursite.in/bilder/9780199738663/titel.jpg"; imageitem.LoadIimage();
{ "language": "en", "url": "https://stackoverflow.com/questions/7509248", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ORA-01427: single-row subquery returns more than one row update...?? Help? My Query returns this error ORA-01427: single-row subquery returns more than one row update, This is my query Update Table_b B Set B.Material_Desc = (Select A.Material_Desc From Table_a A Where A.PartNo = B.PartNo) I have two different tables : Table_a and Table_b, both have same columns PartNo and Material_Desc. I want the Material_Desc in Table_b to update the Material_Desc in Table_a when PartNo are equals. The above query returns the ORA-01427 error, Please can anyone correct my query ? A: The problem is your subquery is returning a whole bunch of rows where you should have only one. You can't do this like this. Depending on the SQL database you're using, something like this should work better : UPDATE Table_b B SET B.Materiel_Desc = A.Materiel_Desc INNER JOIN Table_a A ON A.PartNo = B.PartNo It is possible you must adapt the syntax to your database. For example, I think you cannot do it like this with MySQL. According to http://dev.mysql.com/doc/refman/5.0/en/update.html you should do : UPDATE Table_b, Table_A SET Table_b.Materiel_Desc = Table_A.Materiel_Desc WHERE Table_b.PartNo = Table_a.PartNo;
{ "language": "en", "url": "https://stackoverflow.com/questions/7509250", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Encoding a binary tree structure to json format I have a python binary tree class like this: class BinaryTree: def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right def __unicode__(self): return '%s' % self.data and I have tree traversal function like this: def tree_traversal(tree): if tree: for node_data in tree_traversal(tree.left): yield node_data for node_data in tree_traversal(tree.right): yield node_data now I'm getting stuck in generating a data format like the below nested structure: {'id':1,children:[{'id':2, children:[{'id':3, 'id':4}]}]} the tree structure is: 1 | 2 (left)3 (right)4 A: What you'll need to do is to make your class serializable into a data structure of dictionaries and strings. I didn't find any general way of doing this, so what I usually do is make the BinaryTree implement some sort of or "flattening" and "parsing" function. A good way of doing this is this: import json class BinaryTree: def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right def flatten(self): return { "data" : self.data, "left" : self.left.flatten() if self.left else None, "right" : self.right.flatten() if self.right else None, } @classmethod def from_dictionary(cls, d): obj = cls(d["data"]) if d.has_key("left") and d["left"] is not None: obj.left = cls.from_dictionary(d["left"]) if d.has_key("right") and d["right"] is not None: obj.right = cls.from_dictionary(d["right"]) return obj if __name__ == "__main__": binary_tree = BinaryTree.from_dictionary({"data": "hello", "left": {"data" : "yo"}}) json_data = json.dumps(binary_tree.flatten()) print "JSON: %s" % json_data binary_tree_from_json = BinaryTree.from_dictionary(json.loads(json_data)) print binary_tree_from_json.data print binary_tree_from_json.left.data A: -- edited -- what value do you want to hold in each node? if it is just an int as your example showed, it should be easy enough: a node has an id, one or more children, and a value: { "1" : { "children" : ["2"] , "value" : 1111 }, "2" : { "children" : ["3","4"] , "value" : 2222 }, "3" : { "children" : null , "value" : 3333 }, "4" : { "children" : null , "value" : 4444 } } A: If you are familiar with stack, you can see code below. """ @param root: The root of binary tree. @return: Preorder in list which contains node values. """ def preorderTraversal(self, root): if root is None: return [] stack = [root] preorder = [] while stack: node = stack.pop() preorder.append(node.val) if node.right: stack.append(node.right) if node.left: stack.append(node.left) return preorder
{ "language": "en", "url": "https://stackoverflow.com/questions/7509258", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: did javascript or jquery has method as Server.UrlEncode() in asp.net did javascript or jquery has method as Server.UrlEncode() in asp.net eg:when using $.get("a.aspx?pk=1&k="+kvale, function(data) { dosth(data); }); url must encode A: You can convert any string to a URL-encoded string (suitable for transmission as a query string or, generally speaking, as part of a URL) using the JavaScript functions escape, encodeURI and encodeURIComponent. escape('https://www.stackoverflow.com/?wow.php') "https%3A//www.stackoverflow.com/%3Fwow.php" Source: http://www.javascripter.net/faq/escape.htm
{ "language": "en", "url": "https://stackoverflow.com/questions/7509263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: setting MIME type in asp.net I have a site and in the Chrome inspector, I get this: Resource interpreted as Font but transferred with MIME type application/octet-stream. Where do I setup the MIME types in the asp.net framework (not through the IIS console) so that I remove this warning? I'm using a font I downloaded from font squirrel with a .ttf file extension. Thanks. A: Ok, No access to IIS: The key here is instead of linking to your font file in the html or css, you create a asp.net document that sets its own mime type and then sends the contents of the font file. A sample page load function of myfont.aspx: (completed with your appropriate data) Response.ContentType = "YourMimeType/Type" Response.AddHeader("Header Name", "Header value") Response.WriteFile("font.ttf") Response.End() Response.Clear() Then link to myfont.aspx This is a technique that can be used for any different file type too: Intelligently serve up images through myimage.aspx, generate csv files, whatever. Here are a few sources of varying technicality: http://weblogs.asp.net/stoianbucovich/archive/2008/05/26/using-http-header-to-send-file.aspx http://www.xefteri.com/articles/show.cfm?id=8 http://forums.asp.net/p/1204802/2109808.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7509266", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Getting NSDecimalNumberOverflowException Error I'm getting an error at line: if (! [self.event.managedObjectContext save:&error]). It only happens when the user does not enter another number into the textField, so it is 0. - (void)viewWillAppear:(BOOL)animated { self.textField.text = 0; [super viewWillAppear:YES]; } - (void)addProperty { NSDecimalNumber *decimal = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%@", self.textField.text]]; event.carPayment = decimal; NSError *error = nil; if (! [self.event.managedObjectContext save:&error]) { // Handle the error. } NSLog(@"%@", error); } Error: 2011-09-21 20:31:28.101 Calculator[2391:707] Serious application error. Exception was caught during Core Data change processing. This is usually a bug within an observer of NSManagedObjectContextObjectsDidChangeNotification. NSDecimalNumber overflow exception with userInfo (null) 2011-09-21 20:31:28.144 Calculator[2391:707] *** Terminating app due to uncaught exception 'NSDecimalNumberOverflowException', reason: 'NSDecimalNumber overflow exception' A: I can't tell exactly what you are trying to do, but how about using try-catch syntax to handle the exception and display a message to the user that the value is not permitted to be 0. This assumes it really is not permitted to be 0 or makes no sense for it to be 0. If it does make sense for it to be 0, then try-catch is probably not what you are after.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509270", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What can I do to Makefile.PL so that when I run make test it runs the test suite with dancer environment set to 'test'? I would like to be able to just type "make test" in a dancer app toplevel source directory (the one that was generated by "dancer -a appname") and have it run the tests with the environment set to 'test'. Or if anyone can point me to repository that I can refer to as a sort of "best practice for developing dancer app" for this that would be great! A: You could modify the makefile to set the DANCER_ENVIRONMENT variable appropriately. If I had my druthers, just using Dancer::Test would automatically set the environment though. A: I did some checking and found the following thread on the dancer-users mailing list: http://lists.perldancer.org/pipermail/dancer-users/2011-March/001277.html In a nutshell; In your test files include: use Dancer::Test; Dancer::set environment => 'testing'; Dancer::Config->load; Don't do: use Dancer; I've not tested this though; but the user from the post states that it worked for them....
{ "language": "en", "url": "https://stackoverflow.com/questions/7509278", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: getting checked checkbox display name I have a set of checkboxes: <input type="checkbox" value="111" name="checkbox" id="1">india <input type="checkbox" value="121" name="checkbox" id="21">pak <input type="checkbox" value="131" name="checkbox" id="31">china <!-- ... --> <input type="checkbox" value="141" name="checkbox" id="10">srilanka I want to get the display name of checked check boxes like if india , pak ... I tried with following code which gives me value 111,121, .... field= document.form.checkbox; for(var i=0; i < field.length; i++) { if(document.getElementById(i).checked==true) Cities+=document.classifiedForm.checkbox[i].value + ","; } A: you can set some other some other property in checkbox to be the name of the country, I think you can set it as class, <input type="checkbox" value="111" class="India" id="1">india <input type="checkbox" value="121" class="Pak" id="21">pak and in javascript, field= document.form.checkbox; for(var i=0; i < field.length; i++) { if(document.getElementById(i).checked==true) Cities+=document.classifiedForm.checkbox[i].getAttribute("class")+ ","; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7509281", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I set proper file permission to developer in this setup? I am using Arch Linux on a web development machine, and have a multi-vhost setup with the root directories of each vhost under: /var/www/vhosts Apache2 is using the user/group: http/http If I setup the files to be owned by my user and the http group then apache cannot access them. If I setup the files to be owned by http and the users group then I have no access. I am trying to move from a Windows development machine to Linux since right now I am doing PHP MySQL work. How can I get around this issue so that my user can create and edit files without needing to worry about breaking access for apache each time? A: I use Arch as well quite a lot and instead like the approach of using a limited user's home directory instead of /var/www/vhosts. For instance, you could have a user named sites, ensure that they're not apart of any admin groups and then have the sites in /home/sites/site1, /home/sites/site2, etc… Then make sure that those directories are 644 and files 75: find . -type f -print0 | xargs -0 chmod 0664 # For files find . -type d -print0 | xargs -0 chmod 0755 # For directories
{ "language": "en", "url": "https://stackoverflow.com/questions/7509283", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: (Non-interactive/Line-oriented) command line email inbox viewer tool, configurable for any imap? After using Taskwarrior to manage my todo list from the command line, I'd like to do something similar with email. A program that behaves like the below. Am I imagining something that doesn't exist, or can existing tools do this? I don't believe pine or mutt have any non-interactive invocation modes. They take you to their own shells, which I don't want. I want to be able to pipe the output into another unix command. $ mail_program list inbox From Subject Received ---- ------- ---- mom re: Hi 2011-09-17 $ mail_program list inbox | grep mom mom re: Hi 2011-09-17 $ A: you have the mail or even mailx program. That are interactive, but if you just want to print out your mails you can run $ mail -p $ mailx -r
{ "language": "en", "url": "https://stackoverflow.com/questions/7509287", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: ui datepicker not working as expected on click I have the following piece if code: $(".ui-datepicker-calendar tbody tr").live('click', function(){ $(".ui-datepicker-calendar tbody tr:nth-child(" + ($(this).index() + 1) + ")").css("border", "1px solid Green"); }); but when I click on a date, the green box isn't being shown. However, when the page loads, the green box is shown as expected. What is wrong? A: You can do it a bit differently, perhaps more effectively. You could attach a click event on the datepicker and find the selected day by looking for the TD with .ui-datepicker-current-day class. One other thing is, try to avoid editing css directly; use classes instead. $('.week-picker').datepicker().click(function(event) { $(".ui-datepicker-current-day").parent().addClass('highlight'); }); See this in action: http://jsfiddle.net/william/YQ2Zw/22/. Update If you also want the selected date not to be highlighted, you can remove the .ui-state-active class from the anchor element. E.g. $('.week-picker').datepicker().click(function(event) { $(".ui-datepicker-current-day").parent().addClass('highlight'); $(".ui-datepicker-current-day a").removeClass('ui-state-active'); }); See this in action: http://jsfiddle.net/william/YQ2Zw/24/.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509289", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: NoClassDefFoundError: wrong name I wrote a java program to test RESTful web services by using Netbeans7.0.1 and it works fine there. Now I wrote the build.xml file to compile the code and when I try to run the generated .class file I always got this exception: Exception in thread "main" java.lang.NoClassDefFoundError: ClientREST (wrong name: clientrest/ClientREST) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClassCond(ClassLoader.java:632) at java.lang.ClassLoader.defineClass(ClassLoader.java:616) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141) at java.net.URLClassLoader.defineClass(URLClassLoader.java:283) at java.net.URLClassLoader.access$000(URLClassLoader.java:58) at java.net.URLClassLoader$1.run(URLClassLoader.java:197) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:190) at java.lang.ClassLoader.loadClass(ClassLoader.java:307) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at java.lang.ClassLoader.loadClass(ClassLoader.java:248) Could not find the main class: ClientREST. Program will exit. The name and path are correct, so any thoughts why I'm getting this exception? A: To further note on Garry's reply: The class path is the base directory where the class itself resides. So if the class file is here - /home/person/javastuff/classes/package1/subpackage/javaThing.class You would need to reference the class path as follows: /home/person/javastuff/classes So to run from the command line, the full command would be - java -cp /home/person/javastuff/classes package1/subpackage/javaThing i.e. the template for the above is java_executable -cp classpath the_class_itself_within_the_class_path That's how I finally got mine to work without having the class path in the environment A: Probably the location you are generating your classes in doesnt exists on the class path. While running use the jvm arg -verbose while running and check the log whether the class is being loaded or not. The output will also give you clue as to where the clasess are being loaded from, make sure that your class files are present in that location. A: Try the below syntax: Suppose java File resides here: fm/src/com/gsd/FileName.java So you can run using the below syntax: (Make current directory to 'fm') java src.com.gsd.FileName A: I encountered this error using command line java: java -cp stuff/src/mypackage Test where Test.java resides in the package mypackage. Instead, you need to set the classpath -cp to the base folder, in this case, src, then prepend the package to the file name. So it will end up looking like this: java -cp stuff/src mypackage.Test A: Exception in thread "main" java.lang.NoClassDefFoundError: ClientREST So, you ran it as java ClientREST. It's expecting a ClientREST.class without any package. (wrong name: clientrest/ClientREST) Hey, the class is trying to tell you that it has a package clientrest;. You need to run it from the package root on. Go one folder up so that you're in the folder which in turn contains the clientrest folder representing the package and then execute java clientrest.ClientREST. You should not go inside the clientrest package folder and execute java ClientREST. A: Suppose you have class A and a class B public class A{ public static void main(String[] args){ .... ..... //creating classB object new classB(); } } class B{ } this issue can be resolved by moving class B inside of class A and using static keyword public class A{ public static void main(String[] args){ .... ..... //creating class B new classB(); static class B{ } } A: Here is my class structure package org.handson.basics; public class WithoutMain { public static void main() { System.out.println("With main()..."); } } To compile this program, I had to use absolute path. So from src/main/java I ran: javac org/handson/basics/WithoutMain.java Initially I tried with the below command from basics folder and it didn't work basics % java WithoutMain Error: Could not find or load main class WithoutMain Caused by: java.lang.NoClassDefFoundError: org/handson/basics/WithoutMain (wrong name: WithoutMain) Later I went back to src\main\java folder and ran the class with relevant package structure, which worked as expected. java % java org.handson.basics.WithoutMain With main()... A: I also have encountered this error on Windows when using Class.forName() where the class name I use is correct except for case. My guess is that Java is able to find the file at the path (because Windows paths are case-insensitive) but the parsed class's name does not match the name given to Class.forName(). Fixing the case in the class name argument fixed the error.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509295", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "69" }
Q: window.openDatabase throws SECURITY_ERR in a WebKit-based OSX App I'm writing a webkit-based osx application with a bundle of javascript files. I setup the webView like that: webview = [[WebView alloc] init]; [webview setPolicyDelegate:self]; [webview setFrameLoadDelegate:self]; [webview setUIDelegate:self]; [webview setResourceLoadDelegate:self]; WebPreferences* prefs = [webview preferences]; [prefs setUsesPageCache:YES]; [prefs _setLocalStorageDatabasePath:@"/tmp/test"]; // existed folder, writable [prefs setAllowUniversalAccessFromFileURLs:YES]; // enable cross-domain xmlhttprequest [prefs setAllowFileAccessFromFileURLs:YES]; [prefs setJavaScriptCanAccessClipboard:YES]; [prefs setDatabasesEnabled:YES]; // enable localDatabase [prefs setLocalStorageEnabled:YES]; // enable localStorage [prefs setDeveloperExtrasEnabled:YES]; NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"html" inDirectory:@"data"]; NSURL *fileURL = [NSURL fileURLWithPath:filePath]; [webview.mainFrame loadRequest:[NSURLRequest requestWithURL:fileURL]]; Here is a part of the code of data/test.html.the alert function is hooked to NSLog the message. function test(){ alert("startup"); if(window.localStorage){ alert("local storage works"); }else{ alert("local storage not supported"); } localStorage.setItem('testItem', "hello world; local storage works!"); alert(localStorage.getItem('testItem')); if(window.openDatabase){ alert("local database works"); window.openDatabase("mydb", "1.0", "my first database", 2 * 1024 * 1024); }else{ alert("local database not supported"); } return true; } Here is the log: startup local storage works hello world; local storage works! local database works CONSOLELOG:17 @ SECURITY_ERR: DOM Exception 18: An attempt was made to break through the security policy of the user agent. @ file:///path/of/my.app/Contents/Resources/data/test.html I don't know why window.openDatabase works but cannot create a database. Thank you. A: See my answer here: https://stackoverflow.com/a/8975014/146099 The solution I posted worked for me. There are also other links with slightly different solutions that might work better for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509306", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to set base language other than English in iPhone app? I am implementing an app which is going to have localization. But in this case I need to set base language as Portuguese and not English While implementation my app is going to be in English and after that when i change settings to language Portuguese it will show in that language, but User is going to change the language from app itself and should be able to switch the language A: In plist file set "Localization native development region " set "German". u want to set German. Must have German Localize string file. A: What do you mean by "set the base language"? The app will launch in whatever language the user has his device set to use. If I set the language on my phone to English the app will launch in English. If I set the language of my device to Portuguese the app will launch in Portuguese. If you don't want it to be able to launch in English, don't add localization support for English. Edit I see what your intention is now. Yes, you can use the "AppleLanguages" preference, like so: [[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"en", @"pr", nil] forKey:@"AppleLanguages"]; This will make English the primary language of your app, and if an English translation is not available for a string then it will check the next language in the array for a translation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509307", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Form not Posting in Django I'm trying to do some pretty basic form posts with Django, but whenever I try to click on the button to submit the information nothing happens. No errors or messages of any kind show up in terminal or in developer in Chrome. There is no JS on this page just straight html: <form method="post" action="/"> {% csrf_token %} <input type="text" id="name" name="name"/> <input type="text" id="password" name="password"/> <input type="button" value="Sign Up!"/> </form> My view for this page is pretty straightforward as well: def sign_up(request): return render_to_response('portal/signup.html', context_instance=RequestContext(request)) I'm really baffled as to what is going on, I've been following this to learn authentication. Everything works but I thought adding a "create user" would be a next step. I can't seem to get any form of any kind to work on other pages as well. Any help would be great, I'm going crazy! A: I think that your problem is that you're using <input type="button" value="Sign Up!"/> instead of <input type="submit" value="Sign Up!"/> the input submit will send all the form data to the server, the input button won't. You can learn a little bit more about forms here : http://www.w3schools.com/html/html_forms.asp
{ "language": "en", "url": "https://stackoverflow.com/questions/7509308", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: When loading view tab-bar not displayed - noob question I Have a TabView control, and when the user clicks on the tab item, the view will load. When the view is loaded, there is a button on the view, and when i click on the button, another view gets loaded, i used the following code to load the view: NextView *next = [[NextView alloc]initWithNibName:nil bundle:nil]; [self presentModalViewController:next animated:NO]; But when the view loads, the tab bar items are not displayed. It loads on top of the tab bar items. how can i make the view pop out with the tab bar items ? A: NextView *next = [[NextView alloc]initWithNibName:@"yourNibName" bundle:nil]; [self presentModalViewController:next animated:YES]; if you are using presentModalViewController then you can't display the tabBar instead you can use pushViewController
{ "language": "en", "url": "https://stackoverflow.com/questions/7509314", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: What is the reason for this Valgrind error? Valgrind is complaining with a substr invocation. string Message::nextField(string& input) { int posSeparator = input.find_first_of(SEPARATOR); string temp; temp = input.substr(0, posSeparator); //Error points to this line input.erase(0, posSeparator + 1); return temp; } The error goes: 290 bytes in 12 blocks are definitely lost in loss record 1 of 1 What the function does is basically parse the input, returning portions of string separated by SEPARATOR character. This function is invoked from another class's method with the next definition: void doSomething(string input) { input.erase(0,2); string temp = nextField(input); this->room = atoi(temp.c_str()); temp = input; this->money = atoi(temp.c_str()); } There's nothing else weird or important enough to be included here. I use the default setup for Valgrind from Eclipse Indigo's Valgrind profiling. Any ideas? A: It is probably not a bug in your code. This error could be reported due to details of implementation of C++ standard library. To verify this try the following from Valgrind FAQ: With GCC 2.91, 2.95, 3.0 and 3.1, compile all source using the STL with -D__USE_MALLOC. Beware! This was removed from GCC starting with version 3.3. With GCC 3.2.2 and later, you should export the environment variable GLIBCPP_FORCE_NEW before running your program. With GCC 3.4 and later, that variable has changed name to GLIBCXX_FORCE_NEW. A: You probably have an error somewhere else in your source. I tried to replicate the error using the following code: #include <string> #include <iostream> #include <cstdlib> using namespace std; const char SEPARATOR = ':'; struct Foo { public: int room; int money; void doSomething(string input) { input.erase(0,2); string temp = nextField(input); this->room = atoi(temp.c_str()); temp = input; this->money = atoi(temp.c_str()); } string nextField(string& input) { int posSeparator = input.find_first_of(SEPARATOR); string temp; temp = input.substr(0, posSeparator); //Error points to this line input.erase(0, posSeparator + 1); return temp; } }; int main() { Foo f; f.doSomething("--234:12"); std::cout << f.room << " - " << f.money << std::endl; } Then a ran valgrind: valgrind --tool=memcheck <executable> and the output was: HEAP SUMMARY: in use at exit: 0 bytes in 0 blocks total heap usage: 2 allocs, 2 frees, 61 bytes allocated All heap blocks were freed -- no leaks are possible For counts of detected and suppressed errors, rerun with: -v ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 4 from 4) So, probably your problem is not in this part of code A: You don't check if the posSeparator is actually different from string::npos - this might cause problems in the erase. It's a wild shot, but it might fix a bug anyway.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509318", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: incorrect mysql syntax uploading form information into database This is the error i am receiving and this is my code. I am not sure what the error is since line one is only my ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1. Code: <?php $hostname ="localhost"; $db_user = "root"; $db_password = ""; $database = "Special_order_form"; $db_table = "FORMS"; $db = mysql_connect ($hostname, $db_user, $db_password); mysql_select_db($database,$db); ?> <html> <h1><b><center>SPECIAL ORDER/BACK ORDER FORM</center></b></h1> <body> <?php if (isset($_REQUEST['Submit'])) { $sql = "INSERT INTO $db_table (MANUFACTURER, WAREHOUSE, ORDERTYPE, SOLDTO, SHIPFROM, STOREFROM, SHIPMETH, PO, DAY, ACCNT#, CUSTPO, SHIPPINGADDY, SHIPCUSTVIA, SHIPPINGINSTR, FOB, CASHSALE) values('" . mysql_real_escape_string(stripslashes($_REQUEST['MANUFACTURER'])) . "','" . mysql_real_escape_string(stripslashes($_REQUEST['WAREHOUSE'])) . "','" . mysql_real_escape_string(stripslashes($_REQUEST['ORDERTYPE'])) . "','" . mysql_real_escape_string(stripslashes($_REQUEST['SOLDTO'])) . "','" . mysql_real_escape_string(stripslashes($_REQUEST['SHIPFROM'])) . "','" . mysql_real_escape_string(stripslashes($_REQUEST['STOREFROM'])) . "','" . mysql_real_escape_string(stripslashes($_REQUEST['SHIPMETH'])) . "','" . mysql_real_escape_string(stripslashes($_REQUEST['PO'])) . "','" . mysql_real_escape_string(stripslashes($_REQUEST['DAY'])) . "','" , mysql_real_escape_string(stripslashes($_REQUEST['ACCNT#'])) . "','" , mysql_real_escape_string(stripslashes($_REQUEST['CUSTPO'])) . "','" , mysql_real_escape_string(stripslashes($_REQUEST['SHIPPINGADDY'])) . "','" , mysql_real_escape_string(stripslashes($_REQUEST['SHIPCUSTVIA'])) . "','" , mysql_real_escape_string(stripslashes($_REQUEST['SHIPPINGINSTR'])) . "','" , mysql_real_escape_string(stripslashes($_REQUEST['FOB'])) . "','" , mysql_real_escape_string(stripslashes($_REQUEST['CASHSALE'])) . "')"; if($result = mysql_query($sql ,$db)) { echo '<h1>Thank you</h1>Your information has been entered into our database<br><img src=""'; } else { echo "ERROR: ".mysql_error(); } } else { ?> <center> <table border="1"> <th>MANUFACTURER <br /> <form method="post" action=""> <textarea name="MANUFACTURER" cols="20" rows="3" required> </textarea><br> </th> <th>WAREHOUSE # <select option="" name="WAREHOUSE"required> <option value="none" selected="selected"></option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> </select> </th> <th> <form action =""> <select option="" name="ORDERTYPE"required> <option value="none" selected="selected">Select an option</option> <option value="Back Order">Back Order</option> <option value="Special Order">Special Order</option> <option value="Stock Request">Stock Request</option> </select> </th> <th> </th> <tr> </tr> <th>SOLD TO</th> <th>SHIP FROM FACTORY DIRECT TO:</th> <th>ORDER VIA:</th> <th>DO NOT WRITE IN THIS BOX <br /> PURCHASING USE ONLY</th> <tr> <td><form method="post" action="" required> <textarea name="SOLDTO" cols="20" rows="9" required> </textarea><br> </td> <td> <center> <input type="radio" name="SHIPFROM" value="VIKING WAREHOUSE" required> VIKING WAREHOUSE <br> <input type="radio" name="SHIPFROM" value="AIH STORE"> AIH STORE #<form action ="" required> <select option="" name="FROMSTORE"> <option value="0" selected="selected"></option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> </select required> <br /> <input type="radio" name="SHIPFROM" value="CUSTOMER (DROP SHIP)" required> CUSTOMER (DROP SHIP) </center> </td> <td><SELECT MULTIPLE SIZE=10 name="SHIPMETH"required> <OPTION VALUE="o1">Next Stock Order <OPTION VALUE="o2">TR Trucking <OPTION VALUE="o3">Fed Ex- One Day <OPTION VALUE="o4">Fed Ex- Second Day <OPTION VALUE="o5">Fed Ex- Ground <OPTION VALUE="o6">DHL <OPTION VALUE="o7">UPS Red(Overnight) <OPTION VALUE="o8">UPS Blue(2-Day) <OPTION VALUE="o9">UPS Ground <OPTION VALUE="o10">Other </SELECT></td> <td><center> P.O. <input type="text" name="PO"> <br> DATE: <input type="text" name="DAY"> </center></td> </td> <tr> <td>ACCOUNT #<br /> <form method="post" action=""> </textarea><br><input type="text" name="ACCNT#" required> <br/>Customer Purchase<br/> Order # <br/><input type="text" name="CUSTPO"> </td> <td>SHIPPING ADDRESS: <br/> <form method="post" action=""> <textarea name="SHIPPINGADDY" cols="40" rows="5"> </textarea><br>SHIP TO CUST FROM<br/> AIH VIA <input type="text" name="SHIPCUSTVIA" required> </td> <td>Special Shipping Instructions<br/><form method="post" action=""> <textarea name="SHIPPINGINSTR" cols="20" rows="5"> </textarea><br> </td> <td><center>Sell FOB Point<form action=""> <select name="FOB" required> <option value="none" selected="selected">Make A selection</option> <option value="Anchorage">Anchorage</option> <option value="Factory">Factory</option> <option value="Seattle">Seattle</option> <option value="Other">Other</option> </select> </center></td> <tr> <td> CASH SALE <input type="checkbox" name="CASHSALE" value="CASH SALE" /><br/> COLLECT 50% DEPOSIT <td></td> <td></td> <td>MINIMUM SPECIAL ORDER $50.00 <br/>(Note: EXCEPT WITH STOCK ORDER<br/> STANDARD PACK QUANTITY<br/> MUST APPLY ON ALL ORDERS)</td> </table> <input type="submit" name="Submit" value="Submit"></center> <?php } ?> </form> </form> </body> </html> A: Try putting ACCNT# in backticks like this `ACCNT#`. For good practice you should enclose your table names and column names in your queries. You can also echo your $sql variable and inspect the query if you are having problems. Sometimes that can help show the issue. A: For further information, see the sql reference manual here for more information on using special characters such as # in your table names.. An identifier may be quoted or unquoted. If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it. (Exception: A reserved word that follows a period in a qualified name must be an identifier, so it need not be quoted.) http://dev.mysql.com/doc/refman/5.1/en/identifiers.html I personally try to avoid special characters and to have a fixed approach to table names (i.e. either full words or consistent abbreviations) as I find it minimises confusion and mistakes later.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509319", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: new vs. new (featuring malloc!) In C++, it's standard to always use new over malloc(). However, in this question, the most portable way of overloading the new operator while avoiding platform specific code is to place a call to malloc() within it to do the actual allocation. When overloaded, constructors are called and type-safety is kept. In addition, you can monitor and control how memory is allocated. My question, when used in this capacity, are there still any downsides to using malloc() within C++? A: If you wish to override new and delete then you pretty much have to use malloc and free. That's how it is meant to be done. Do not be afraid. The downsides of using malloc() outside of the implementation of new() remain. A: The biggest downside I can think off is you can't explicitly call delete or delete [] on a pointer that has been allocated using malloc() without invoking undefined behavior. If you are going to go the highly un-recommended path and use malloc() to allocate memory explicitly for C++ objects, then you are still going to have to call placement new in order to properly call a constructor to initialize the memory location allocated by malloc(). Without an operator new wrapper on malloc(), you'll also have to test to make sure you do not get a NULL return value, and create some code to handle cases where you do without the benefit of throwing an exception. It's also very dangerous, and can incur a number of undefined behaviors, if you simply tried to use C-library functions like memcpy() to copy C++ objects into heap memory allocated with malloc(). Furthermore, because you utilized placement new for your object construction, you are going to have to explicitly call the destructuors for your dynamically allocated objects, and then explicitly call free() on the pointers. This again can cause all sorts of problems if it's not handled correctly, especially if you wanted to work with polymorphic types and virtual base-classes. If you are going to work with just malloc() and free(), a nice rule of thumb to avoid undefined behavior pitfalls is to keep the objects you allocate and deallocate with malloc() and free() to POD-types. That means non-polymorphic structs or classes with no user-defined constructors, destructors, copy-constructors, assignment operators, private/protected non-static data-members, or base-classes, and all the non-static data-members of the struct/class are POD-types themselves. Since POD-types are basically C-style structs (but with the added ability to define non-static methods and a this pointer), you can safely do C-style memory management with them. A: You stated it yourself... the downside to using malloc/free directly in C++ code is that constructors and destructors will not be run; using new/delete ensures that constructors and destructors are run. However, there is nothing wrong with indirectly using malloc via the new/delete operators.
{ "language": "en", "url": "https://stackoverflow.com/questions/7509320", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: I/O C++ Reading from a text file In my program I'm inputting a file and inside the file is something like this: 11267 2 500.00 2.00 ...that is one line. There are more lines set up in that same order. I need to input the first number, 11267, into actnum. After that, 2 into choice, etc. I simply lack the logic to figure out how to input just the first 5 numbers into the first variable. actnum = 11267; choice = 2; Edit* I have all of that: #include <fstream> #include <iostream> using namespace std; void main() { int trans = 0, account; float ammount, bal; cout << "ATM" << endl; etc etc I just dont know how to get it to only input the specific numbers into it. Like when I do the >>actnum >> choice how does it know to put just the first 5 numbers in it? A: Use the C++ <fstream> library. fscanf() is slightly out of date and you will probably get better performance from <fstream>, not to mention that the code is a lot easier to read: #include <fstream> using namespace std; ifstream fileInput("C:\foo.txt"); fileInput >> actnum >> choice >> float1 >> float2; A: fscanf is what you are looking for. it works the same as scanf, but is for files. unsigned int actnum, choice; float float1, float2; FILE *pInputFile = fopen("input.txt", "r"); fscanf(pInputFile, "%u %u %f %f", &actnum, &choice, &float1, &float2); A: input_file_stream >> actnum >> choice >> ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7509323", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }