text
stringlengths
8
267k
meta
dict
Q: wait(), notify() and notifyAll() inside synchronized statement I get following error when trying to do invoke notifyAll() inside a synchronized statement: Invoked Object.notify() outside synchronized context. Example: final List list = new ArrayList(); synchronized(list) {..... invoked notifyAll() here}; A: You can only call wait(), notify(), and notifyAll() on the object that is being synchronized on: synchronized (list) { //... list.notifyAll(); } In other words, the calling thread must own the object's monitor. If, inside synchronized (list), you call notifyAll(), you are actually calling notifyAll() on this rather than list. A: My guess is that you are calling notifyAll() on a different object, one for which you don't hold a lock. In your example, you may call notifyAll() on list, but not on this. A: A thread must own the lock on the object it's invoking wait, notify, notifyAll on. In the code you posted, the thread owns the lock on 'list' and then it calls notifyAll on 'this' object.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504475", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: AJAX shopping cart for ASP.NET site Could you please recommend me good free solution for AJAX shopping cart for ASP.NET site. Actually I already have my own shopping cart on my site, but it works with redirects like you clicked on "Add To Cart" button, it sends the page (postback) to server and redirect me to ShowCart page where added item is there. I need some javascript to not redirect to shopping cart page. It should work like: click on "Add To Cart" button, page not reload or redirect, ajax banner appear at the top of the page and shows all items (include just added) in the shopping cart. Thanks a lot! A: Check out the eCommerce section of the windows web applications gallery. A: NopCommerce is very good, the last edition is web forms and the most recent version is MVC. A: Take a look at these: Vista Cart dashcommerce A: Here is exactly what I searched: http://www.webresourcesdepot.com/wp-content/uploads/file/jbasket/sliding-basket/
{ "language": "en", "url": "https://stackoverflow.com/questions/7504481", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to resize regions allocated by VirtualAlloc? I would like to resize a region of memory allocated by MS window's VirtualAlloc. Looking at the VirtualFree documentation, it is possible to decommit a region only partly, but it's not possible to partially release it. That is, it's possible to release part of the physical memory, but not part of the virtual memory. I'm aware it may be necessary to reallocate the region in such a case. However, copying over the entire region would be rather inefficient. Is there a way to ask windows to allocate a new region with a different size, that points to the same memory? A: As you have mentioned, it does not appear to be possible to partially release a range of reserved pages because the VirtualFree() documentation states: If the dwFreeType parameter is MEM_RELEASE, [lpAddress] must be the base address returned by the VirtualAlloc function when the region of pages [was] reserved. as well as: If the dwFreeType parameter is MEM_RELEASE, [dwSize] must be 0 (zero). VirtualFree() is itself a thin wrapper of the kernel function NtFreeVirtualMemory(). Its documentation page (the same as for ZwFreeVirtualMemory()) also has this wording. One possible work-around is to split up a single, large reservation with multiple smaller ones. For example, suppose that you normally reserve 8 MiB of virtual address space at a time. You could instead attempt to reserve the range in thirty-two contiguous 256 KiB reservations. The first 256 KiB reservation would contain a 32-bit unsigned bit field, where the ith bit is set if the ith 256 KiB reservation was obtained: #define NOMINMAX #include <windows.h> #include <assert.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #define RESERVATION_SIZE (256*1024) typedef struct st_first_reservation { size_t reservation_size; uint32_t rfield; char premaining[0]; } st_first_reservation; int main() { SYSTEM_INFO sys_info = { 0 }; GetSystemInfo(&sys_info); assert((RESERVATION_SIZE % sys_info.dwPageSize) == 0); void *vp = VirtualAlloc(NULL, 32*RESERVATION_SIZE, MEM_RESERVE, PAGE_NOACCESS); if (VirtualFree(vp, 0, MEM_RELEASE) == 0) { fprintf(stderr, "Error: VirtualFree() failed.\n"); return EXIT_FAILURE; } st_first_reservation *pfirst_reservation = (st_first_reservation *) VirtualAlloc(vp, RESERVATION_SIZE, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); if (pfirst_reservation == NULL) { pfirst_reservation = (st_first_reservation *) VirtualAlloc(NULL, RESERVATION_SIZE, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); if (pfirst_reservation == NULL) { fprintf(stderr, "Error: VirtualAlloc() failed.\n"); return EXIT_FAILURE; } } fprintf(stderr, "pfirst_reservation = 0x%p\n", (void *) pfirst_reservation); pfirst_reservation->reservation_size = RESERVATION_SIZE; pfirst_reservation->rfield = 1LU; char *p = (char *) pfirst_reservation; unsigned i = 1; for (; i < 32; ++i) { vp = VirtualAlloc(p += RESERVATION_SIZE, RESERVATION_SIZE, MEM_RESERVE, PAGE_NOACCESS); if (vp != NULL) { assert(((void *) vp) == p); pfirst_reservation->rfield |= 1LU << i; fprintf(stderr, "Obtained reservation #%u\n", i + 1); } else { fprintf(stderr, "Failed to obtain reservation #%u\n", i + 1); } } fprintf(stderr, "pfirst_reservation->rfield = 0x%08x\n", pfirst_reservation->rfield); return EXIT_SUCCESS; } Sample output: pfirst_reservation = 0x009A0000 Obtained reservation #2 Obtained reservation #3 Obtained reservation #4 Obtained reservation #5 Obtained reservation #6 Obtained reservation #7 Obtained reservation #8 Obtained reservation #9 Obtained reservation #10 Obtained reservation #11 Obtained reservation #12 Obtained reservation #13 Obtained reservation #14 Obtained reservation #15 Obtained reservation #16 Obtained reservation #17 Obtained reservation #18 Obtained reservation #19 Obtained reservation #20 Obtained reservation #21 Obtained reservation #22 Obtained reservation #23 Obtained reservation #24 Obtained reservation #25 Obtained reservation #26 Obtained reservation #27 Obtained reservation #28 Obtained reservation #29 Obtained reservation #30 Obtained reservation #31 Obtained reservation #32 pfirst_reservation->rfield = 0xffffffff EDIT: I have found that it is much better to "pre-reserve" the thirty-two 256 KiB ranges all at once, free, and then try to re-reserve as many as you can. I updated the code and sample output above. In a multithreaded environment, the code may fall back to the "place anywhere" allocation of the first reservation. Perhaps it is a good idea to attempt reserving RESERVATION_SIZE bytes at a reserved-then-freed range of 32*RESERVATION_SIZE bytes five or so times, finally falling back to the "place anywhere" allocation. A: Not an answer, but I have to ask: Considering the pain you're in, the performance hits of VirtualAlloc( ), and the non-portability of your code; as against any value VIrtualAlloc( ) gives, could you perhaps consider using malloc( ) and friends instead? IOW, does VirtualAlloc( ) confer any real advantage? In my opinion (maybe only my opinion), the power and generality of malloc( ) outweigh any of the allure that VirtualAlloc( ) promises. And it would let you deal with your regions much more straightforwardly. Sorry for the non-answer. I hate it when folks ask "who ever would even think to do that?" But of course it's all different when I'm the one asking "why" :-) A: If you want to shrink an allocation, you can use VirtualFree with MEM_DECOMMIT on a subrange of the allocation. Note that this won't free up address space; only physical RAM. If you want to grow it, you can try VirtualAlloc passing an address immediately after your existing allocation. This may, of course, fail, at which point you need to copy memory. You can also try using GlobalAlloc with GMEM_MOVEABLE and GlobalReAlloc (or the equivalent Heap* functions). If you need to free address space, you might want to try using anonymous memory-mapping objects, and changing their mapped window at run-time - or simply use 64-bit to get additional address space.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504482", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Rails HTTP streaming with HAML There appears to be an issue with using HTTP streaming with HAML projects in rails. It works perfectly if I use ERB instead. Apparently, I'm not the only one with this problem. It doesn't work with placing stream at the top of the controller, or with using render :stream => true in the action. How can I get HAML and HTTP streaming to play nicely together? Update: I've opened an issue on the gem's page, here. A: This is not yet supported by HAML (source): HTTP streaming is the sort of thing that would require a substantial set of modifications to the core Haml engine. It's only moderately tricky to get it working even in basic cases, but when you factor in things like the whitespace-eating operators it gets much more difficult. This isn't something I'm opposed to in theory, but it's also not something that's high on my priority list given the difficulty of implementing it. A: The internals of Haml are such that it is indeed writing out to a buffer as it goes along. However, the "standard" API that Rails has traditionally provided for templating languages is a fairly straightforward in-and-out call. I don't think Haml does currently have "streaming support", but its simply more of an API issue than anything else. I'm curious as to how Rails is plugging into ERB to do this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504492", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Django project: location of model definition used by multiple other models Given separate applications for both movies and books, for instance, where would I define models / tables such as genre, which reference both movies and books? Do I define it in whichever application I create first, and then reference that in the second? That doesn't seem right at all, but I've not worked out a better way. A: A third, common application for "genre" makes the most sense. Then movies and books both import this additional (common) application.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is iBatis the right choice for dynamic SQL queries? I'm facing the following design issue: * *There will be several prepared SQL statements where the WHERE-clause contains defined contraints in which the values will be dynamic, based on user input. *In addition there will be some SQL statements required that might end up to be pretty complex, but the resulting SELECT-clause) will still be pretty straight-forward. As far as I understand iBatis would fit into these requirements. * *Now what happens in a scenario where the user (through a UI) would influence the complete query construction, making the queries on an adhoc basis? A prepared statement can't do it as the whole WHERE clause is dynamic, we might even have aggregation clauses or even sub-selects built into the SQL functions. With all of this in mind, would you still go with iBatis or do some other custom development as the best architecture given the above requirements? A: Latest version of iBatis (MyBatis) is allowing us to use powerful OGNL based expressions for constructing dynamic queries. One of the most powerful features of iBATIS has always been its Dynamic SQL capabilities. A: iBatis would work in this case. We did the exact same scenario you described using iBatis to create dynamic, adhoc queries, based on user selections from the UI. The complexity arose as the number of user elements that were made available increased from page to page, but it is doable. Hibernate is a fully functional ORM that is another obvious option, but it's more complex to use. Here are some links to help: Dynamic Queries with Hibernate StackOverflow question on Dynamic Queries with Hibernate So I would go with iBatis as a first choice, or Hibernate as a solution. I think with the complexity a custom solution would too easily turn into a lot of convoluted, nested code, unless you really think through the entire design first. Assuming of course that the requirements don't change as you go. I feel iBatis would allow you to better organize the sql code in the endeavor and allow for flexibility in the design in lieu of future changes. IMHO. A: I would vote for iBatis. I have always found it best if you have complex SQL queries to be executed (especially a number of JOINs and SUB-selects) that result in a trivial result set. You have a lot more control over SQL when you use iBatis, and also helps you integrate with existing/legacy databases.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504502", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Nokogiri Xpath Double Looping What I'm trying to do is pul the code block that contains the td with the class default. This works perfectly fine. But then I need to sort out the different parts of the code block. When I try to do this with the second xpath call what it does is each time it prints all the comheads in each of the blocks def HeaderProcessor(doc) doc.xpath("//td[@class='default']").each do |block| puts block.xpath("//span[@class='comhead']").text end end When I just print out block each block prints out once and contains the comment header and the comment. When I try to run the xpath it prints out EVERY comhead found in doc and seems to be ignoring the block variable. Any ideas on how I can make this work? What am I miss understanding about xpath? UPDATE: <td class="default"> <div style="margin-top:2px; margin-bottom:-10px; "> <span class="comhead"> #some data </span></div> <br><span class="comment"><font color="#000000">#some more data</span> </td> A: You're telling Nokogiri to search from the root when you say //span[@class='comhead'], you just want */span[@class='comhead']: doc.xpath("//td[@class='default']").each do |block| block.xpath("*/span[@class='comhead']").each do |span| puts span.text end end or even just this: doc.xpath('//td[@class="default"]/*/span[@class="comhead"]').each do |span| puts span.text end if you don't need to do anything with the <td> elements.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504505", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Java detect if class is a proxy Is it possible to detect if a class is a proxy (dynamic, cglib or otherwise)? Let classes Aand B implement a common interface I. Then I need to define a routine classEquals of signature public boolean classEquals(Class<? extends I> a, Class<? extends I> b); such that it evaluates to true only if a.equals(b) or Proxy(a).equals(b), where Proxy(a) denotes a dynamic proxy of type A (dynamic, cglib or otherwise). With the assistance of @Jigar Joshi, this is what it looks like so far: public boolean classEquals(Class a, Class b) { if (Proxy.isProxyClass(a)) { return classEquals(a.getSuperclass(), b); } return a.equals(b); } The problem is that it doesn't detect e.g., a CGLIB proxy. A: no, in general you can't tell if an object is a proxy. and that's simply because it's hard to define what is a proxy. you can implement an interface and use it as a proxy, you can use cglib, asm, javassist, plastic, jdk or generate bytecode on the fly by yourself. it is no different than loading xxx.class file. what you are thinking about is probably checking if the object is created by cglib, asm or other specific library. in such case - usually yes. most libraries have their own fingerprint that can be discovered. but in general it's not possible A: Proxy.isProxyClass(Foo.class) A: If instanceof is acceptable, then clazz.isInstance(b) should work as well. Edit: I wrote that before reading your modified answer. There is a similar method for classes as well: b.isAssignableFrom(a)
{ "language": "en", "url": "https://stackoverflow.com/questions/7504509", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: SEO: Can dynamically generated links be crawled? I have a page containing <div> tags with onclick="" code that calls an ajax request to get json data, and then iterates through the results to form links (<a />) to append to the page. These links do not exist in any other place on my website. How can I make these dynamically generated links crawlable? My initial thought was to turn the <div> tags into <a> tags with a href="#", but with my limited knowledge of how typical crawlers work, i don't think this would solve my problem since the "#" would be what's recognized by the crawler, and not necessarily the dynamically generated output. This is besides the point that i don't want the scroll positioning to be altered at all, which would also rule out giving the <a> tag an id and having it reference itself. Do I have any options aside from making a new page containing all of the links i need to be crawled? Thanks. A: As a general rule, content that is created or made available through JavaScript cannot be found or indexed by search engines. Google does support crawlable Ajax but using it as the only means of accessing your content is bad for accessibility. Also, other search engines can't get to that content which is also not a good thing. Basically crawable ajax is a bad thing. You should always make your content available without requiring JavaScript to get it. Then you can improve your site by adding JavaScript to make getting the content faster or easier. This is called Progressive Enhancement and is how good websites are built.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Modify Django AutoField start value I have and existing database, which I have migrated with SQLAlchemy to a new PostgreSQL database. I moved all primary keys with the same values as before. Now I have tables filled with data, but the associated sequences starts from 1. I have pk values stored 1 to 2000. Now, when I try to save something with Django, I have the duplicate key value violates unique constraint regarding to the Primary Key. How can I modify the sequence start values or escape this situation? My current solution is: conn = psycopg2.connect(...) for table_name in table_names: cursor = conn.cursor() cursor.execute(""" SELECT setval('%s_id_seq', (SELECT COALESCE(MAX(id),0)+1 FROM %s)); """% (table_name, table_name)) It works for me, but I don't like it. A: Ways to set / reset a sequence in PostgreSQL (not necessarily to max(id)). * *There's the simple way you have in the question. You can set the sequence to start at an arbitrary number with setval(): SELECT setval('tbl_id_seq'); *Then there's the standard SQL way with ALTER SEQUENCE doing the same: ALTER SEQUENCE myseq RESTART WITH 1; *If you like to restart your sequences at numbers other than the default 1: CREATE TABLE foo(id serial, a text); -- creates sequence "foo_id_seq" INSERT INTO foo(a) VALUES('a'); -- seq. starts with --> 1 ALTER SEQUENCE foo_id_seq START WITH 10; -- doesn't restart sequence INSERT INTO foo(a) VALUES('b'); --> 2 ALTER SEQUENCE foo_id_seq RESTART; -- restarts sequence INSERT INTO foo(a) VALUES('c'); --> 10 *And there is another way, when you empty a table with TRUNCATE: TRUNCATE foo RESTART IDENTITY; Implicitly executes ALTER SEQUENCE foo_id_seq RESTART;
{ "language": "en", "url": "https://stackoverflow.com/questions/7504513", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Create a combined view list in SharePoint 2007 I like to have a main page Web part with a link to each one of the shared documents in our portal. The problem is that they are from different libraries and also I want the SharePoint to keep track of check in and check outs of the files. When I use, Content Editor to add the links, and then click on the list, it download a copy of file and saved changes do not change the original document. I thought about creating a modified view in that specific library and filter out just one file. Then put that file in the front page. But, the first problem is that the file is 2 or 3 level deep in hierarchy. Also, even if I manage to do that, what should I do about different files in different libraries? Please Advise
{ "language": "en", "url": "https://stackoverflow.com/questions/7504514", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Google maps and plus one conflict When you put a google map and a plus one button on the same page it seems to create some strange rendering issues. In these examples WITH and WITHOUT the plus one button. If you click on a marker it will zoom in on it, then hit reset to zoom back out. You'll see the map doesn't render when the buttons included till you zoom in and out manually. Why? Anyone know a way around this? EDIT: This issue seems to only happen in Google Chrome...IRONY! A: Both worked fine for me in Firefox 6. In IE9 the google +1 button didn't even show up at all. No surprise there, really, although it should work. That might be, however, because you don't have fully valid HTML in your test document (with html and body tags). You might want to try that first. You can also try using the HTML 5 tag for the google plus one button. I feel that is a safer alternative and it is fully HTML5-valid: <div class="g-plusone" data-size="medium" data-annotation="inline" data-width="250" ></div> Check out the +1 Button Reference under "+1 Tag Attributes" for a complete list of possible attributes
{ "language": "en", "url": "https://stackoverflow.com/questions/7504518", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: problem getting value from HashMap Hi all I'm using a HashMap to hold one of my object with a string key. when I put an object with a key it has no problem, when I put my second object I got my object added but can't get it with its key. Somewhat it goes to somewhere that is "next". I took a screenshot from debug mode (eclipse), below although size shows 2, I can't see my second item in hashmap, but in other hashmap's next node. To note something I use my key like in a form "name.tag", tag and name in same time can never be the same, but "tag" can be the same. does hashmap has something to do with dot operator when evaluating keys? I hope I could write clearly, Thanks in advance Edit: Here is a piece of code I use to create my hashmap private HashMap<String,ParameterItem> parseParametersNode(DataModel parent,Element element){ NodeList parameterChilds=element.getChildNodes();//gep element parameters HashMap<String, ParameterItem> parameterItems=new HashMap<String, ParameterItem>(); for(int i=0;i<parameterChilds.getLength();i++){ if(parameterChilds.item(i).getNodeType()==Node.ELEMENT_NODE){ Element el=(Element) parameterChilds.item(i); NamedNodeMap atts=el.getAttributes(); ParameterItem item=new ParameterItem(); for(int j=0;j<atts.getLength();j++){ Attr attribute=(Attr) atts.item(j); String attributeValue=attribute.getValue(); String attributeName=attribute.getName(); item.setParsedProperty(attributeName, attributeValue); } /*check attributes later*/ //finish loop and insert paramitem to params String key="key"+i; if(item.getTag()!=null && item.getName()!=null) key=item.getName()+"."+item.getTag(); parameterItems.put(key, item); // testParam=item; // parameterItems.put(key, testParam); } } return parameterItems; } A: You have the code: String key="key"+i; but right after this you set key again not adding to it: if(item.getTag()!=null && item.getName()!=null) key=item.getName()+"."+item.getTag(); Should this be key +=item.getName()+"."+item.getTag(); ? A: There is not really a problem here: you have a hash collision. That is, both of your keys have been placed in the same hash bucket. It appears you have only four buckets (odd, I thought the initial default was 10 or 16), so the chance of that with random data is 25 percent. Your size incremented just fine. The next is the internal implementation’s way of pointing to the next element in the same bucket. If the number of elements in each buckets gets too big, Java will internally rehash into more buckets. I do not see why you need a HashTable here since you are numbering your keys consecutively (you could use an ArrayList), but maybe this is just starter code and your real use case is different.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504519", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: NHibernate projecting a collection of elements I want to select all requests that are outstanding for a given manager. A manager can have multiple teams. I compose the queries applying various restrictions based upon permissions, and alter the queries to provide row counts, existence checks, sub queries, etc. The composition makes use of QueryOver, though using ICriteria instead would also be acceptable. Given the following classes; class Team { public virtual int Manager { get; set; } public virtual ISet<int> Members { get; set; } } class Request { public virtual int Owner { get; set; } public virtual bool IsOutstanding { get; set; } } class static SomeRestrictions { public static void TeamsForManager<TRoot> (this IQueryOver<TRoot, Team> query, int managerId) { // In reality this is a little more complex query.Where (x => x.Manager == managerId); } } This is the current query that I'm trying (which doesn't work). var users = QueryOver.Of<Team> (); users.TeamsForManager (5) users.Select (/* not sure */); var requests = session.QueryOver<Request> () .Where (x => x.IsOutstanding) .WithSubquery.WhereProperty (x => x.Owner).In (users); The HQL to select the users would be: "SELECT m FROM Team t JOIN t.Members m WHERE <TeamsForManager restrictions>" But I don't want to use HQL because I can't then compose it with other restrictions based upon permissions. I also wouldn't be able to compose it with other queries to turn it into row counts/existence checks, etc. A: i saw you changed the model but this would have been the way var users = QueryOver.Of<Team> (); users.TeamsForManager (5); users.JoinAlias(t => t.Members, () => membervalue).Select(() => membervalue);
{ "language": "en", "url": "https://stackoverflow.com/questions/7504527", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I add asset search paths to Sprockets based on a wildcard subdomain in rails 3.1? The Rails Asset Pipeline guide instructs you to use config.assets.paths in config/application.rb but I don't have access to the request's subdomain at this point. I'd like to be able to prepend an extra path (for the current request only) based on the request's subdomain. My application specific details It's a basic CMS app. The root domain.com host handles the administrative part with standard controller/view rendering and default asset paths. Requests to subdomain.domain.com renders the site based on subdomain. It calls prepend_view_path in a before_filter and adds Rails.root.join('vendor/sites/[subdomain]/templates') for the current request only. I'd like to be able to prepend Rails.root.join('vendor/sites/[subdomain]/assets') to the Sprockets search paths when the request host is [subdomain].domain.com. EDIT I ended up just dropping in a mixin for Sprockets::Environment that overwrites the call method: module SiteAssetsResolver def call(env) begin # prepend path based on subdomain (from env) super # Sprockets::Server#call ensure # remove path based on subdomain end end end MyApp::Application.assets.extend(SiteAssetsResolver) A: Just as you did for your view path, add a before filter and append the new path to Rails.application.config.assets.paths I got this idea while watching Railscasts #279 Understanding the Asset Pipeline A: I agree with commenter on your question that said "The asset pipeline isn't really meant to be compiling your assets each request in production." -- making it not really possible to do exactly what you ask. So how about an alternative to accomplish what you're really trying to accomplish here, which is different asset resolution for different subdomains. Put your sub-domain specific assets in sub-directories of your asset folders. Now, in the view/helpers, when you call asset_path or any other helpers that take a relative asset path, ask it for "#{subdomain}/name_of_asset" instead of just "name_of_asset". Now, because of the way the asset compiler works, it's possible this subdirectory method won't work, you may have to put the subdomain at the beginning of the actual filename instead. "#{subdomain}_name_of_asset". Not sure. And this still wouldn't give you a sort of 'default fall through' where some assets in some subdomains don't have subdomain-specific assets, they just 'fall through' to the default. Which would be nice. It's possible a way can be figured out to do that too, not sure. But at any rate, following this approach of asking for a different asset at display-time using logic in view/helper.... is going to get you further than your original suggested approach, which probably isn't possible.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504529", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: jQuery tmpl() for MooTools? Is there a library for MooTools analogous to jQuery-tmpl library? A: The MooTools Template Engine is the closest you'll probably come. Update: Scratch that, MooTools Forge looks promising.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504530", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I change the position of a view in a Linear Layout.? So I have a Linear Layout already populated with children. Is there a way to change the position at which one of the children is located? I'm trying to swap to views between them if that's of any help. final LinearLayout parrent = (LinearLayout)findViewById(R.id.llWidgetScreen); final LinearLayout Delailah = new LinearLayout(this); Delailah.setLayoutParams(new android.widget.LinearLayout.LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT)); AppWidgetHostView wedgy = attachWidget(mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo)); Delailah.addView(wedgy); final Button btn = new Button(this); btn.setLayoutParams(new android.widget.LinearLayout.LayoutParams((int)(20*scale +0.5f), android.view.ViewGroup.LayoutParams.FILL_PARENT, 0f)); btn.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { parrent.removeView(Delailah); return false; } }); btn.setBackgroundColor(mainColor); btn.setText(parrent.getChildCount()+1+""); btn.setTextColor(textColor); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(ReadyForDrag==0) { btn.setBackgroundColor(actiColor); ReadyForDrag++; DragPosition1=Integer.parseInt(btn.getText().toString()); } else if(ReadyForDrag==1) { btn.setBackgroundColor(actiColor); ReadyForDrag=0; LinearLayout v1 = (LinearLayout)parrent.getChildAt(DragPosition1); LinearLayout v2 = (LinearLayout)parrent.getChildAt(Integer.parseInt(btn.getText().toString())); //move view 2 to position 1 //move view 1 to position 2 } } }); Delailah.addView(btn); parrent.addView(Delailah); A: You can use ViewGroup.removeView(View) and ViewGroup.addView(View child, int index, ViewGroup.LayoutParams params) for this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504531", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Why does my IP address keep ending up in hosts.deny file? At my organisation we've set up a linux server which runs one of our sites. It's been working fine and I have been able to SSH through into it (using Terminal on OSX) no problem. As of earlier when I tried to ssh root@123.123.123.123 (not my real IP) I was rejected with: ssh_exchange_identification: Connection closed by remote host Having a look at the /etc/hosts.deny file I can see: sshd: 123.123.123.123 in the list. This means the IP which I have been using for months no problem has suddenly appeared in the list. I removed it, and was able to SSH in fine, ONCE, then on my second try I was rejected and looking at the list again, I can see we have been added to the list once more! I have added our IP to the hosts.allow file, but no luck - still no access. Why do IP's appear in the hosts.deny file? How can I stop our IP appearing there? A: As mentioned, probably a fail2ban or similar (look for denyhosts too - another popular). The usual fix is to append your IP address to /etc/hosts.allow This works for denyhosts at least A: You may have a system like fail2ban installed which adds you to the hosts.deny file if you enter your password incorrectly a few times..
{ "language": "en", "url": "https://stackoverflow.com/questions/7504536", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Run script if screen size greater than value I'm working on a home page which has a basic image fader: <div id="cycle"> <img src="/images/bath.jpg"> <img src="/images/desk.jpg"> <img src="/images/car.jpg"> </div> At the foot of the document I've got some jQuery: jQuery(document).ready(function($){ if ($(window).width() > 480) { $('#cycle').fadeIn(4000).cycle({ timeout: 8000, speed: 4000 }); } }); So, I only want this script to run if the screen width is greater than 480px on load. Is this the best way of doing that? I guess I could hide the .cycle div using media queries, but I don't then want the script doing its thing in the background. Is the only way to have the .cycle div fade in on resize to use: $(window).resize(function() {}); ? A: Would something like this work for you. Here is a fiddle example ... fiddle code here function checkSize(){ if ($(window).width() > 480) { cycleImages(); }else{ $('#cycle').fadeOut().cycle('stop'); } } function cycleImages(){ $('#cycle').fadeIn(4000).cycle({ timeout: 8000, speed: 4000 }); } checkSize(); $(window).resize(function() { checkSize(); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7504537", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: VBA Simple Copying one Range to Another Range This is a really simple VBA formula but it's failing. It's only pasting into cell A6 onwards. Is it just me? Excel 2011 by the way. Range("A4:A5").Select Selection.Copy Range("A6:A1000").Select ActiveSheet.Paste A: I think the issue is that you have two different values in A4 and A5 and so excel can only repeat those values in the paste range if the paste range is an even number of cells. This works for me: Range("A4:A5").Copy Destination:=Range("A6:A1001") Note that A6:1001 is 996 cells (an even number). Using A6:A1000 is 995 and is an odd number so excel cannot work out how to repeat your values from A4 to A5. I think this is the issue...but happy to be educated otherwise...
{ "language": "en", "url": "https://stackoverflow.com/questions/7504543", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Convert uiwebview to pdf and emailing I have a Uiwebview which shows local htmls.I've done to convert html to pdf and can read on desktop.But when I attached pdf file to mail,It sent successfully but sometimes those pdfs can not be read in ipad or iphone?who has any suggestions to help me? Thanks in advance,
{ "language": "en", "url": "https://stackoverflow.com/questions/7504545", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: View-based NSTableView with rows that have dynamic heights I have an application with a view-based NSTableView in it. Inside this table view, I have rows that have cells that have content consisting of a multi-row NSTextField with word-wrap enabled. Depending on the textual content of the NSTextField, the size of the rows needed to display the cell will vary. I know that I can implement the NSTableViewDelegate method -tableView:heightOfRow: to return the height, but the height will be determined based on the word wrapping used on the NSTextField. The word wrapping of the NSTextField is similarly based on how wide the NSTextField is… which is determined by the width of the NSTableView. Soooo… I guess my question is… what is a good design pattern for this? It seems like everything I try winds up being a convoluted mess. Since the TableView requires knowledge of the height of the cells to lay them out... and the NSTextField needs knowledge of it's layout to determine the word wrap… and the cell needs knowledge of the word wrap to determine it's height… it's a circular mess… and it's driving me insane. Suggestions? If it matters, the end result will also have editable NSTextFields that will resize to adjust to the text within them. I already have this working on the view level, but the tableview does not yet adjust the heights of the cells. I figure once I get the height issue worked out, I'll use the -noteHeightOfRowsWithIndexesChanged method to inform the table view the height changed… but it's still then going to ask the delegate for the height… hence, my quandry. A: For anyone wanting more code, here is the full solution I used. Thanks corbin dunn for pointing me in the right direction. I needed to set the height mostly in relation to how high a NSTextView in my NSTableViewCell was. In my subclass of NSViewController I temporary create a new cell by calling outlineView:viewForTableColumn:item: - (CGFloat)outlineView:(NSOutlineView *)outlineView heightOfRowByItem:(id)item { NSTableColumn *tabCol = [[outlineView tableColumns] objectAtIndex:0]; IBAnnotationTableViewCell *tableViewCell = (IBAnnotationTableViewCell*)[self outlineView:outlineView viewForTableColumn:tabCol item:item]; float height = [tableViewCell getHeightOfCell]; return height; } - (NSView *)outlineView:(NSOutlineView *)outlineView viewForTableColumn:(NSTableColumn *)tableColumn item:(id)item { IBAnnotationTableViewCell *tableViewCell = [outlineView makeViewWithIdentifier:@"AnnotationTableViewCell" owner:self]; PDFAnnotation *annotation = (PDFAnnotation *)item; [tableViewCell setupWithPDFAnnotation:annotation]; return tableViewCell; } In my IBAnnotationTableViewCell which is the controller for my cell (subclass of NSTableCellView) I have a setup method -(void)setupWithPDFAnnotation:(PDFAnnotation*)annotation; which sets up all outlets and sets the text from my PDFAnnotations. Now I can "easily" calcutate the height using: -(float)getHeightOfCell { return [self getHeightOfContentTextView] + 60; } -(float)getHeightOfContentTextView { NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:[self.contentTextView font],NSFontAttributeName,nil]; NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:[self.contentTextView string] attributes:attributes]; CGFloat height = [self heightForWidth: [self.contentTextView frame].size.width forString:attributedString]; return height; } . - (NSSize)sizeForWidth:(float)width height:(float)height forString:(NSAttributedString*)string { NSInteger gNSStringGeometricsTypesetterBehavior = NSTypesetterLatestBehavior ; NSSize answer = NSZeroSize ; if ([string length] > 0) { // Checking for empty string is necessary since Layout Manager will give the nominal // height of one line if length is 0. Our API specifies 0.0 for an empty string. NSSize size = NSMakeSize(width, height) ; NSTextContainer *textContainer = [[NSTextContainer alloc] initWithContainerSize:size] ; NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:string] ; NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init] ; [layoutManager addTextContainer:textContainer] ; [textStorage addLayoutManager:layoutManager] ; [layoutManager setHyphenationFactor:0.0] ; if (gNSStringGeometricsTypesetterBehavior != NSTypesetterLatestBehavior) { [layoutManager setTypesetterBehavior:gNSStringGeometricsTypesetterBehavior] ; } // NSLayoutManager is lazy, so we need the following kludge to force layout: [layoutManager glyphRangeForTextContainer:textContainer] ; answer = [layoutManager usedRectForTextContainer:textContainer].size ; // Adjust if there is extra height for the cursor NSSize extraLineSize = [layoutManager extraLineFragmentRect].size ; if (extraLineSize.height > 0) { answer.height -= extraLineSize.height ; } // In case we changed it above, set typesetterBehavior back // to the default value. gNSStringGeometricsTypesetterBehavior = NSTypesetterLatestBehavior ; } return answer ; } . - (float)heightForWidth:(float)width forString:(NSAttributedString*)string { return [self sizeForWidth:width height:FLT_MAX forString:string].height ; } A: This got a lot easier in macOS 10.13 with .usesAutomaticRowHeights. The details are here: https://developer.apple.com/library/content/releasenotes/AppKit/RN-AppKit/#10_13 (In the section titled "NSTableView Automatic Row Heights"). Basically you just select your NSTableView or NSOutlineView in the storyboard editor and select this option in the Size Inspector: Then you set the stuff in your NSTableCellView to have top and bottom constraints to the cell and your cell will resize to fit automatically. No code required! Your app will ignore any heights specified in heightOfRow (NSTableView) and heightOfRowByItem (NSOutlineView). You can see what heights are getting calculated for your auto layout rows with this method: func outlineView(_ outlineView: NSOutlineView, didAdd rowView: NSTableRowView, forRow row: Int) { print(rowView.fittingSize.height) } A: I was looking for a solution for quite some time and came up with the following one, which works great in my case: - (double)tableView:(NSTableView *)tableView heightOfRow:(long)row { if (tableView == self.tableViewTodo) { CKRecord *record = [self.arrayTodoItemsFiltered objectAtIndex:row]; NSString *text = record[@"title"]; double someWidth = self.tableViewTodo.frame.size.width; NSFont *font = [NSFont fontWithName:@"Palatino-Roman" size:13.0]; NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName]; NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:text attributes:attrsDictionary]; NSRect frame = NSMakeRect(0, 0, someWidth, MAXFLOAT); NSTextView *tv = [[NSTextView alloc] initWithFrame:frame]; [[tv textStorage] setAttributedString:attrString]; [tv setHorizontallyResizable:NO]; [tv sizeToFit]; double height = tv.frame.size.height + 20; return height; } else { return 18; } } A: Since I use custom NSTableCellView and I have access to the NSTextField my solution was to add a method on NSTextField. @implementation NSTextField (IDDAppKit) - (CGFloat)heightForWidth:(CGFloat)width { CGSize size = NSMakeSize(width, 0); NSFont* font = self.font; NSDictionary* attributesDictionary = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName]; NSRect bounds = [self.stringValue boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:attributesDictionary]; return bounds.size.height; } @end A: Have you had a look at RowResizableViews? It is quite old and I haven't tested it but it may nevertheless work. A: Here's what I have done to fix it: Source: Look into XCode documentation, under "row height nstableview". You'll find a sample source code named "TableViewVariableRowHeights/TableViewVariableRowHeightsAppDelegate.m" (Note: I'm looking at column 1 in table view, you'll have to tweak to look elsewhere) in Delegate.h IBOutlet NSTableView *ideaTableView; in Delegate.m table view delegates control of row height - (CGFloat)tableView:(NSTableView *)tableView heightOfRow:(NSInteger)row { // Grab the fully prepared cell with our content filled in. Note that in IB the cell's Layout is set to Wraps. NSCell *cell = [ideaTableView preparedCellAtColumn:1 row:row]; // See how tall it naturally would want to be if given a restricted with, but unbound height CGFloat theWidth = [[[ideaTableView tableColumns] objectAtIndex:1] width]; NSRect constrainedBounds = NSMakeRect(0, 0, theWidth, CGFLOAT_MAX); NSSize naturalSize = [cell cellSizeForBounds:constrainedBounds]; // compute and return row height CGFloat result; // Make sure we have a minimum height -- use the table's set height as the minimum. if (naturalSize.height > [ideaTableView rowHeight]) { result = naturalSize.height; } else { result = [ideaTableView rowHeight]; } return result; } you also need this to effect the new row height (delegated method) - (void)controlTextDidEndEditing:(NSNotification *)aNotification { [ideaTableView reloadData]; } I hope this helps. Final note: this does not support changing column width. A: This is a chicken and the egg problem. The table needs to know the row height because that determines where a given view will lie. But you want a view to already be around so you can use it to figure out the row height. So, which comes first? The answer is to keep an extra NSTableCellView (or whatever view you are using as your "cell view") around just for measuring the height of the view. In the tableView:heightOfRow: delegate method, access your model for 'row' and set the objectValue on NSTableCellView. Then set the view's width to be your table's width, and (however you want to do it) figure out the required height for that view. Return that value. Don't call noteHeightOfRowsWithIndexesChanged: from in the delegate method tableView:heightOfRow: or viewForTableColumn:row: ! That is bad, and will cause mega-trouble. To dynamically update the height, then what you should do is respond to the text changing (via the target/action) and recalculate your computed height of that view. Now, don't dynamically change the NSTableCellView's height (or whatever view you are using as your "cell view"). The table must control that view's frame, and you will be fighting the tableview if you try to set it. Instead, in your target/action for the text field where you computed the height, call noteHeightOfRowsWithIndexesChanged:, which will let the table resize that individual row. Assuming you have your autoresizing mask setup right on subviews (i.e.: subviews of the NSTableCellView), things should resize fine! If not, first work on the resizing mask of the subviews to get things right with variable row heights. Don't forget that noteHeightOfRowsWithIndexesChanged: animates by default. To make it not animate: [NSAnimationContext beginGrouping]; [[NSAnimationContext currentContext] setDuration:0]; [tableView noteHeightOfRowsWithIndexesChanged:indexSet]; [NSAnimationContext endGrouping]; PS: I respond more to questions posted on the Apple Dev Forums than stack overflow. PSS: I wrote the view based NSTableView A: Based on Corbin's answer (btw thanks shedding some light on this): Swift 3, View-Based NSTableView with Auto-Layout for macOS 10.11 (and above) My setup: I have a NSTableCellView that is laid out using Auto-Layout. It contains (besides other elements) a multi-line NSTextField that can have up to 2 rows. Therefore, the height of the whole cell view depends on the height of this text field. I update tell the table view to update the height on two occasions: 1) When the table view resizes: func tableViewColumnDidResize(_ notification: Notification) { let allIndexes = IndexSet(integersIn: 0..<tableView.numberOfRows) tableView.noteHeightOfRows(withIndexesChanged: allIndexes) } 2) When the data model object changes: tableView.noteHeightOfRows(withIndexesChanged: changedIndexes) This will cause the table view to ask it's delegate for the new row height. func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat { // Get data object for this row let entity = dataChangesController.entities[row] // Receive the appropriate cell identifier for your model object let cellViewIdentifier = tableCellViewIdentifier(for: entity) // We use an implicitly unwrapped optional to crash if we can't create a new cell view var cellView: NSTableCellView! // Check if we already have a cell view for this identifier if let savedView = savedTableCellViews[cellViewIdentifier] { cellView = savedView } // If not, create and cache one else if let view = tableView.make(withIdentifier: cellViewIdentifier, owner: nil) as? NSTableCellView { savedTableCellViews[cellViewIdentifier] = view cellView = view } // Set data object if let entityHandler = cellView as? DataEntityHandler { entityHandler.update(with: entity) } // Layout cellView.bounds.size.width = tableView.bounds.size.width cellView.needsLayout = true cellView.layoutSubtreeIfNeeded() let height = cellView.fittingSize.height // Make sure we return at least the table view height return height > tableView.rowHeight ? height : tableView.rowHeight } First, we need to get our model object for the row (entity) and the appropriate cell view identifier. We then check if we have already created a view for this identifier. To do that we have to maintain a list with cell views for each identifier: // We need to keep one cell view (per identifier) around fileprivate var savedTableCellViews = [String : NSTableCellView]() If none is saved, we need to created (and cache) a new one. We update the cell view with our model object and tell it to re-layout everything based on the current table view width. The fittingSize height can then be used as the new height. A: Here is a solution based of JanApotheker's answer, modified as cellView.fittingSize.height was not returning the correct height for me. In my case I am using the standard NSTableCellView, an NSAttributedString for the cell's textField text, and a single column table with constraints for the cell's textField set in IB. In my view controller, I declare: var tableViewCellForSizing: NSTableCellView? In viewDidLoad(): tableViewCellForSizing = tableView.make(withIdentifier: "My Identifier", owner: self) as? NSTableCellView Finally, for the tableView delegate method: func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat { guard let tableCellView = tableViewCellForSizing else { return minimumCellHeight } tableCellView.textField?.attributedStringValue = attributedString[row] if let height = tableCellView.textField?.fittingSize.height, height > 0 { return height } return minimumCellHeight } mimimumCellHeight is a constant set to 30, for backup, but never actually used. attributedStrings is my model array of NSAttributedString. This works perfectly for my needs. Thanks for all the previous answers, which pointed me in the right direction for this pesky problem. A: This sounds a lot like something I had to do previously. I wish I could tell you that I came up with a simple, elegant solution but, alas, I did not. Not for lack of trying though. As you have already noticed the need of UITableView to know the height prior to the cells being built really make it all seem quite circular. My best solution was to push logic to the cell, because at least I could isolate what class needed to understand how the cells were laid out. A method like + (CGFloat) heightForStory:(Story*) story would be able to determine how tall the cell had to be. Of course that involved measuring text, etc. In some cases I devised ways to cache information gained during this method that could then be used when the cell was created. That was the best I came up with. It is an infuriating problem though as it seems there should be a better answer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504546", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "91" }
Q: CSS positioning2 i want my blocks to be centered. every time i open a div it lean to the left. the code is: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>SGKM</title> <style type="text/css"> body{ margin:0 auto; } body { font:13px/22px Arial; color:#444; } .container{ } .container2{ clear:both; } a{ color:#000; } .stage { height:150px; width:200px; border:1px solid #f0f0f0; background:#fafafa; margin:60px auto; } .docIcon { background: #eee; background: -webkit-linear-gradient(top, #ddd 0, #eee 15%, #fff 40%, #fff 70%, #eee 100%); background: -moz-linear-gradient(top, #ddd 0, #eee 15%, #fff 40%, #fff 70%, #eee 100%); background: -o-linear-gradient(top, #ddd 0, #eee 15%, #fff 40%, #fff 70%, #eee 100%); background: -ms-linear-gradient(top, #ddd 0, #eee 15%, #fff 40%, #fff 70%, #eee 100%); background: linear-gradient(top, #ddd 0, #eee 15%, #fff 40%, #fff 70%, #eee 100%); border: 1px solid #ccc; display: block; width: 26px; height: 50px; float:left; text-align:center; } .docIcon2 { background: #eee; background: -webkit-linear-gradient(top, #ddd 0, #eee 15%, #fff 40%, #fff 70%, #eee 100%); background: -moz-linear-gradient(top, #ddd 0, #eee 15%, #fff 40%, #fff 70%, #eee 100%); background: -o-linear-gradient(top, #ddd 0, #eee 15%, #fff 40%, #fff 70%, #eee 100%); background: -ms-linear-gradient(top, #ddd 0, #eee 15%, #fff 40%, #fff 70%, #eee 100%); background: linear-gradient(top, #ddd 0, #eee 15%, #fff 40%, #fff 70%, #eee 100%); border: 1px solid #ccc; display: block; width: 29px; height: 50px; float:right; text-align:center; } .doc3{width: 23px; height: 50px; float:left; border: 1px solid #ccc; text-align:center;} </style> </head> <body> <div class="stage"> <center><h2>Sahne</h2></center> </div> <div class="container"> <a href="#" class="doc3"></a> <a class="doc3"></a> <a href="#" class="doc3"></a> <a href="#" class="docIcon">A<br>24</a> <a href="#" class="docIcon">A<br>23</a> <a href="#" class="docIcon">A<br>22</a> <a href="#" class="docIcon">A<br>21</a> <a href="#" class="docIcon">A<br>20</a> <a href="#" class="docIcon">A<br>19</a> <a href="#" class="docIcon">A<br>18</a> <a href="#" class="doc3"></a> <a href="#" class="doc3"></a> <a href="#" class="docIcon">A<br>17</a> <a href="#" class="docIcon">A<br>16</a> <a href="#" class="docIcon">A<br>15</a> <a href="#" class="docIcon">A<br>14</a> <a href="#" class="docIcon">A<br>13</a> <a href="#" class="docIcon">A<br>12</a> <a href="#" class="docIcon">A<br>11</a> <a href="#" class="docIcon">A<br>10</a> <a href="#" class="docIcon">A<br>9</a> <a href="#" class="docIcon">A<br>8</a> <a href="#" class="doc3"></a> <a href="#" class="doc3"></a> <a href="#" class="docIcon">A<br>7</a> <a href="#" class="docIcon">A<br>6</a> <a href="#" class="docIcon">A<br>5</a> <a href="#" class="docIcon">A<br>4</a> <a href="#" class="docIcon">A<br>3</a> <a href="#" class="docIcon">A<br>2</a> <a href="#" class="docIcon">A<br>1</a> </div> <div class="container2"> <a href="#" class="docIcon">B<br>27</a> <a href="#" class="docIcon">B<br>26</a> <a href="#" class="docIcon">B<br>25</a> <a href="#" class="docIcon">B<br>24</a> <a href="#" class="docIcon">B<br>23</a> <a href="#" class="docIcon">B<br>22</a> <a href="#" class="docIcon">B<br>21</a> <a href="#" class="docIcon">B<br>20</a> <a href="#" class="doc3"></a> <a href="#" class="doc3"></a> <a href="#" class="docIcon">B<br>19</a> <a href="#" class="docIcon">B<br>18</a> <a href="#" class="docIcon">B<br>17</a> <a href="#" class="docIcon">B<br>16</a> <a href="#" class="docIcon">B<br>15</a> <a href="#" class="docIcon">B<br>14</a> <a href="#" class="docIcon">B<br>13</a> <a href="#" class="docIcon">B<br>12</a> <a href="#" class="docIcon">B<br>11</a> <a href="#" class="docIcon">B<br>10</a> <a href="#" class="docIcon">B<br>9</a> <a href="#" class="doc3"></a> <a href="#" class="doc3"></a> <a href="#" class="docIcon">B<br>8</a> <a href="#" class="docIcon">B<br>7</a> <a href="#" class="docIcon">B<br>6</a> <a href="#" class="docIcon">B<br>5</a> <a href="#" class="docIcon">B<br>4</a> <a href="#" class="docIcon">B<br>3</a> <a href="#" class="docIcon">B<br>2</a> <a href="#" class="docIcon">B<br>1</a> </div> <div class="container2"> <a href="#" class="docIcon">G<br>36</a> <a href="#" class="docIcon">G<br>35</a> <a href="#" class="docIcon">G<br>34</a> <a href="#" class="docIcon">G<br>33</a> <a href="#" class="docIcon">G<br>32</a> <a href="#" class="docIcon">G<br>31</a> <a href="#" class="docIcon">G<br>30</a> <a href="#" class="docIcon">G<br>29</a> <a href="#" class="docIcon">G<br>28</a> <a href="#" class="docIcon">G<br>27</a> <a href="#" class="docIcon">G<br>26</a> <a href="#" class="docIcon">G<br>23</a> <a href="#" class="docIcon">G<br>22</a> <a href="#" class="docIcon">G<br>21</a> <a href="#" class="docIcon">G<br>20</a> <a href="#" class="docIcon">G<br>19</a> <a href="#" class="docIcon">G<br>18</a> <a href="#" class="doc3"></a> <a href="#" class="doc3"></a> <a href="#" class="docIcon">G<br>25</a> <a href="#" class="docIcon">G<br>24</a> <a href="#" class="docIcon">G<br>23</a> <a href="#" class="docIcon">G<br>22</a> <a href="#" class="docIcon">G<br>21</a> <a href="#" class="docIcon">G<br>20</a> <a href="#" class="docIcon">G<br>19</a> <a href="#" class="docIcon">G<br>18</a> <a href="#" class="docIcon">G<br>17</a> <a href="#" class="docIcon">G<br>16</a> <a href="#" class="docIcon">G<br>15</a> <a href="#" class="docIcon">G<br>14</a> <a href="#" class="docIcon">G<br>13</a> <a href="#" class="docIcon">G<br>12</a> <a href="#" class="docIcon">G<br>11</a> <a href="#" class="doc3"></a> <a href="#" class="doc3"></a> <a href="#" class="docIcon">G<br>10</a> <a href="#" class="docIcon">G<br>9</a> <a href="#" class="docIcon">G<br>8</a> <a href="#" class="docIcon">G<br>7</a> <a href="#" class="docIcon">G<br>6</a> <a href="#" class="docIcon">G<br>5</a> <a href="#" class="docIcon">G<br>4</a> <a href="#" class="docIcon">G<br>3</a> <a href="#" class="docIcon">G<br>2</a> <a href="#" class="docIcon">G<br>1</a> </body> </html> A: If you are talking about your letters/button kindof block, the reason is quite simple : The all float to the left. The div you called container then do not have any solid element inside them, thus appearing empty. Would this snippet partially fix your problem? .container {margin:0px auto; width:968px;} .container2 {margin:0px auto;width:700px;} a {display:inline-block !important;float:none!important;} Here's what it does : * *Give your container element a max width and center according to this width. (issue : the width is not dynamic, so it doesn't react to the number of element in it... *Reset the floating of a elements and define them as inline-block so that the are next to each other, but still block element (with dimension). Note : I'd advise you to not use this, it's bad code. Rethink your style instead with the information I provided you. A: Well not sure if it that what you wanted, also your HTML Code is not very read-friendly <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>SGKM</title> <style type="text/css"> body { margin: 0px; font: 13px/22px Arial; color: #444; } a { color: #000; } .stage { height: 150px; width: 200px; border: 1px solid #f0f0f0; background: #fafafa; margin: 60px auto; } .docIcon { background: #eee; background: -webkit-linear-gradient(top, #ddd 0, #eee 15%, #fff 40%, #fff 70%, #eee 100%); background: -moz-linear-gradient(top, #ddd 0, #eee 15%, #fff 40%, #fff 70%, #eee 100%); background: -o-linear-gradient(top, #ddd 0, #eee 15%, #fff 40%, #fff 70%, #eee 100%); background: -ms-linear-gradient(top, #ddd 0, #eee 15%, #fff 40%, #fff 70%, #eee 100%); background: linear-gradient(top, #ddd 0, #eee 15%, #fff 40%, #fff 70%, #eee 100%); border: 1px solid #ccc; display: block; width: 26px; height: 50px; float:left; text-align:center; } .docIcon2 { background: #eee; background: -webkit-linear-gradient(top, #ddd 0, #eee 15%, #fff 40%, #fff 70%, #eee 100%); background: -moz-linear-gradient(top, #ddd 0, #eee 15%, #fff 40%, #fff 70%, #eee 100%); background: -o-linear-gradient(top, #ddd 0, #eee 15%, #fff 40%, #fff 70%, #eee 100%); background: -ms-linear-gradient(top, #ddd 0, #eee 15%, #fff 40%, #fff 70%, #eee 100%); background: linear-gradient(top, #ddd 0, #eee 15%, #fff 40%, #fff 70%, #eee 100%); border: 1px solid #ccc; display: block; width: 29px; height: 50px; float: right; text-align:center; } .doc3 { width: 23px; height: 50px; float:left; border: 1px solid #ccc; text-align:center; } .container, .container2 { width: 1300px; margin: auto; } .clear { clear: both; } </style> </head> <body> <div class="stage"> <center><h2>Sahne</h2></center> </div> <div class="container"> <a href="#" class="doc3"></a> <a class="doc3"></a> <a href="#" class="doc3"></a> <a href="#" class="docIcon">A<br>24</a> <a href="#" class="docIcon">A<br>23</a> <a href="#" class="docIcon">A<br>22</a> <a href="#" class="docIcon">A<br>21</a> <a href="#" class="docIcon">A<br>20</a> <a href="#" class="docIcon">A<br>19</a> <a href="#" class="docIcon">A<br>18</a> <a href="#" class="doc3"></a> <a href="#" class="doc3"></a> <a href="#" class="docIcon">A<br>17</a> <a href="#" class="docIcon">A<br>16</a> <a href="#" class="docIcon">A<br>15</a> <a href="#" class="docIcon">A<br>14</a> <a href="#" class="docIcon">A<br>13</a> <a href="#" class="docIcon">A<br>12</a> <a href="#" class="docIcon">A<br>11</a> <a href="#" class="docIcon">A<br>10</a> <a href="#" class="docIcon">A<br>9</a> <a href="#" class="docIcon">A<br>8</a> <a href="#" class="doc3"></a> <a href="#" class="doc3"></a> <a href="#" class="docIcon">A<br>7</a> <a href="#" class="docIcon">A<br>6</a> <a href="#" class="docIcon">A<br>5</a> <a href="#" class="docIcon">A<br>4</a> <a href="#" class="docIcon">A<br>3</a> <a href="#" class="docIcon">A<br>2</a> <a href="#" class="docIcon">A<br>1</a> <div class="clear"></div> </div> <div class="container2"> <a href="#" class="docIcon2">B<br>27</a> <a href="#" class="docIcon2">B<br>26</a> <a href="#" class="docIcon2">B<br>25</a> <a href="#" class="docIcon2">B<br>24</a> <a href="#" class="docIcon2">B<br>23</a> <a href="#" class="docIcon2">B<br>22</a> <a href="#" class="docIcon2">B<br>21</a> <a href="#" class="docIcon2">B<br>20</a> <a href="#" class="docIcon2"></a> <a href="#" class="docIcon2"></a> <a href="#" class="docIcon2">B<br>19</a> <a href="#" class="docIcon2">B<br>18</a> <a href="#" class="docIcon2">B<br>17</a> <a href="#" class="docIcon2">B<br>16</a> <a href="#" class="docIcon2">B<br>15</a> <a href="#" class="docIcon2">B<br>14</a> <a href="#" class="docIcon2">B<br>13</a> <a href="#" class="docIcon2">B<br>12</a> <a href="#" class="docIcon2">B<br>11</a> <a href="#" class="docIcon2">B<br>10</a> <a href="#" class="docIcon2">B<br>9</a> <a href="#" class="docIcon2"></a> <a href="#" class="docIcon2"></a> <a href="#" class="docIcon2">B<br>8</a> <a href="#" class="docIcon2">B<br>7</a> <a href="#" class="docIcon2">B<br>6</a> <a href="#" class="docIcon2">B<br>5</a> <a href="#" class="docIcon2">B<br>4</a> <a href="#" class="docIcon2">B<br>3</a> <a href="#" class="docIcon2">B<br>2</a> <a href="#" class="docIcon2">B<br>1</a> <div class="clear"></div> </div> <div class="container2"> <a href="#" class="docIcon">G<br>36</a> <a href="#" class="docIcon">G<br>35</a> <a href="#" class="docIcon">G<br>34</a> <a href="#" class="docIcon">G<br>33</a> <a href="#" class="docIcon">G<br>32</a> <a href="#" class="docIcon">G<br>31</a> <a href="#" class="docIcon">G<br>30</a> <a href="#" class="docIcon">G<br>29</a> <a href="#" class="docIcon">G<br>28</a> <a href="#" class="docIcon">G<br>27</a> <a href="#" class="docIcon">G<br>26</a> <a href="#" class="docIcon">G<br>23</a> <a href="#" class="docIcon">G<br>22</a> <a href="#" class="docIcon">G<br>21</a> <a href="#" class="docIcon">G<br>20</a> <a href="#" class="docIcon">G<br>19</a> <a href="#" class="docIcon">G<br>18</a> <a href="#" class="doc3"></a> <a href="#" class="doc3"></a> <a href="#" class="docIcon">G<br>25</a> <a href="#" class="docIcon">G<br>24</a> <a href="#" class="docIcon">G<br>23</a> <a href="#" class="docIcon">G<br>22</a> <a href="#" class="docIcon">G<br>21</a> <a href="#" class="docIcon">G<br>20</a> <a href="#" class="docIcon">G<br>19</a> <a href="#" class="docIcon">G<br>18</a> <a href="#" class="docIcon">G<br>17</a> <a href="#" class="docIcon">G<br>16</a> <a href="#" class="docIcon">G<br>15</a> <a href="#" class="docIcon">G<br>14</a> <a href="#" class="docIcon">G<br>13</a> <a href="#" class="docIcon">G<br>12</a> <a href="#" class="docIcon">G<br>11</a> <a href="#" class="doc3"></a> <a href="#" class="doc3"></a> <a href="#" class="docIcon">G<br>10</a> <a href="#" class="docIcon">G<br>9</a> <a href="#" class="docIcon">G<br>8</a> <a href="#" class="docIcon">G<br>7</a> <a href="#" class="docIcon">G<br>6</a> <a href="#" class="docIcon">G<br>5</a> <a href="#" class="docIcon">G<br>4</a> <a href="#" class="docIcon">G<br>3</a> <a href="#" class="docIcon">G<br>2</a> <a href="#" class="docIcon">G<br>1</a> <div class="clear"></div> </div> </body> </html> If you want to have the Buttons floated to the left assign the correct class. If you want the content to be centered then set a width for your containers, also your second container2 was not closing. Here you go :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7504548", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Mouse Coordinates in HTML5 Canvas I have tried many different ways of trying to get mouse coordinates in HTML5 canvas in compliment with video and none have seemed too work very well in either Chrome or Safari. At the moment I am using: <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Test</title> <script src="modernizr-1.6.min.js"></script> <script type="text/javascript"> window.addEventListener('load', eventWindowLoaded,false); var videoElement; var VideoDiv; var Object1; var Mouse = { x:0 x:y} function eventWindowLoaded(){ videoElement = document.createElement("video"); videoDiv = document.createElement('div'); document.body.appendChild(videoDiv); videoDiv.appendChild(videoElement); videoDiv.setAttribute("style", "display:none;"); var videoType = supportedVideoFormat(videoElement); if (videoType == ""){ alert("no video support"); return; } videoElement.setAttribute("src", "different_movement>" + videoType); videoElement.addEventListener("canplaythrough", videoLoaded, false); } function supportedVideoFormat(video){ var returnExtension= ""; if(video.canPlayType("video/webm") =="probably" || video.canPlayType("video/webm") == "maybe"){ returnExtension = "webm"; } else if (video.canPlayType("video/mp4") == "probably" || video.canPlayType("video/mp4") == "maybe"){ returnExtension = "mp4"; }else if(video.canPlayType("video/ogg") == "probably" || video.canPlayType("video/ogg") == "maybe"){ returnExtension = "ogv"; } return returnExtension; } function videoLoaded(event){ canvasApp(); } canvasOne.onmousemove = function (event){ Mouse={ x: event.offsetX, y: event.offsetY} } } function canvasApp(){ function drawScreen(){ context.drawImage(videoElement, 0, 0); context.fillStyle = '#ffffff'; context.fillText(Mouse.x, 280, 280); context.fillText(Mouse.y, 280, 300); } var theCanvas = document.getElementByID('canvasOne'); var context = theCanvas.getContext('2d'); videoElement.play(); setinterval(drawScreen, 33); } </script> </head> <body> <canvas id="canvasOne" width="640" height="480"> Your browser does not support HTML5 Canvas. </canvas> </div> </body> </html> The result of this is the 0,0 will be shown on the video from the initial variable set at 0,0 but then instead of changing as the mouse is moved around the screen, it stays 0,0. This leads me to believe that it is the part of the code that is finding the mouse coordinates that is not working. I have tried various other attempts at finding mouse coordinates including: Mouse={ x: event.pageX, y: event.pageX} , if (e.pageY) { posy = e.pageY; } else if (e.clientY) { posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; } , var mouseX; var mouseY; var pieceX; var pieceY; if (e.pageX || e.pageY) { mouseX = e.pageX; mouseX = e.pageY; } else { mouseX = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; mouseY = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; } My end product is supposed to be a video that has mouse interactions that will play sounds when certain parts on the video are clicked (thus the part of video). I have tried not using canvas at all for this, and instead positioning a image on top of the canvas which has image mapping on it, but it doesn't seem to work. Another issue I am going to run into when I figure out mouse coordinates is what I will test collisions with the mouse coordinates to initiate it to play the sounds. EDIT: Completely rewrote the code using e.offset, seems to work. A: I used <iframe> to set an html page with a canvas element positioned top left of document. Then when I get clientX-Y it's origin is the top left of the canvas document, that's in the iframe, that you can have positioned anywhere on the canvas-containing document. It's easy as pie. <iframe scrolling="no" height="100%" width="100%" src="canvas.html"></iframe> also, I got the canvas to scale when it is scaled by style sheet. I added this to my canvas program. c = canvas element, ctx = canvas context; ctx.scale(c.width/630,c.height/800); // I originally intended it to be 630x800 (note: I am not sure if this answers your problem, but it is how I find coordinates without having to offset.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7504551", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Insert data in MySQL through soap? We are working on an Android-app with a database connection (MySQL). Now we would like to insert data of a user in the database. Does anyone know safe methods to do this? Maybe to use php and soap? A: Did you see this? How to call a SOAP web service on Android You could use PHP if you like or any other language that you find most fitting to create a SOAP web service (in the server/web tier). If you don't need to use SOAP and your data/web methods can be expressed as URLs/querystrings you can consider a RESTful web interface.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504553", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to instantiate a listener by reflection in Android I have to develop an application for Android 1.6 (API 4), which should be able to use the OnAudioFocusChangeListener (available since Android 2.2 - API 8) in the phones with Android 2.2 or later. Anyone can tell me how to instantiate a listener by reflection? I have already managed to run static and also non-static methods by reflection, but I don't know how to do with listeners. This is the listener to reflect: AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); OnAudioFocusChangeListener audioListener = new OnAudioFocusChangeListener() { @Override public void onAudioFocusChange(int focusChange) { // code to execute } }; public void getAudioFocus() { audioManager.requestAudioFocus(audioListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN); } public void releaseAudioFocus() { audioManager.abandonAudioFocus(audioListener); } This is a code example with methods I managed to run by reflection: Class BluetoothAdapter = Class.forName("android.bluetooth.BluetoothAdapter"); Method methodGetDefaultAdapter = BluetoothAdapter.getMethod("getDefaultAdapter"); // static method from the BluetoothAdapter class returning a BluetoothAdapter object Object bluetooth = methodGetDefaultAdapter.invoke(null); Method methodGetState = bluetooth.getClass().getMethod("getState"); // non-static method executed from the BluetoothAdapter object (which I called "bluetooth") returning an int int bluetoothState = (Integer) methodGetState.invoke(bluetooth); A: In the end I solved it by using a Proxy class. Here is the code! private AudioManager theAudioManager; private Object myOnAudioFocusChangeListener = null; private static final int AUDIOMANAGER_AUDIOFOCUS_GAIN = 1; private static final int AUDIOMANAGER_AUDIOFOCUS_LOSS = -1; theAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); // instantiating the OnAudioFocusChangeListener by reflection (as it only exists from Android 2.2 onwards) // we use a Proxy class for implementing the listener public void setOnAudioFocusChangeListener() { Log.i(this, "setOnAudioFocusChangeListener()"); Class<?>[] innerClasses = theAudioManager.getClass().getDeclaredClasses(); for (Class<?> interfaze : innerClasses) { if (interfaze.getSimpleName().equalsIgnoreCase("OnAudioFocusChangeListener")) { Class<?>[] classArray = new Class<?>[1]; classArray[0] = interfaze; myOnAudioFocusChangeListener = Proxy.newProxyInstance(interfaze.getClassLoader(), classArray, new ProxyOnAudioFocusChangeListener()); } } } // called by onResume public void getAudioFocus() { if (myOnAudioFocusChangeListener != null) { Log.i(this, "getAudioFocus()"); try { Method[] methods = theAudioManager.getClass().getDeclaredMethods(); for (Method method : methods) { if (method.getName().equalsIgnoreCase("requestAudioFocus")) { method.invoke(theAudioManager, myOnAudioFocusChangeListener, AudioManager.STREAM_MUSIC, AUDIOMANAGER_AUDIOFOCUS_GAIN); Log.i(this, "requestAudioFocus"); } } } catch (Exception e) { Log.e(this, e.getMessage()); } } } // called by onPause public void releaseAudioFocus() { if (myOnAudioFocusChangeListener != null) { Log.i(this, "releaseAudioFocus()"); try { Method[] methods = theAudioManager.getClass().getDeclaredMethods(); for (Method method : methods) { if (method.getName().equalsIgnoreCase("abandonAudioFocus")) method.invoke(theAudioManager, myOnAudioFocusChangeListener); } } catch (Exception e) { Log.e(this, e.getMessage()); } } } PROXY OnAudioFocusChangeListener class private class ProxyOnAudioFocusChangeListener implements InvocationHandler { // implements the method onAudioFocusChange from the OnAudioFocusChangeListener public void onAudioFocusChange(int focusChange) { Log.e(this, "onAudioFocusChange() focusChange = " + focusChange); if (focusChange == AUDIOMANAGER_AUDIOFOCUS_LOSS) { Log.i(this, "AUDIOMANAGER_AUDIOFOCUS_LOSS"); Message msg = mHandler.obtainMessage(ControllerHandler.SET_ON_PAUSE); mHandler.sendMessage(msg); } else if (focusChange == AUDIOMANAGER_AUDIOFOCUS_GAIN) { Log.i(this, "AUDIOMANAGER_AUDIOFOCUS_GAIN"); // no action is taken } } // implements the method invoke from the InvocationHandler interface // it intercepts the calls to the listener methods // in this case it redirects the onAudioFocusChange listener method to the OnAudioFocusChange proxy method public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object result = null; try { if (args != null) { if (method.getName().equals("onAudioFocusChange") && args[0] instanceof Integer) { onAudioFocusChange((Integer) args[0]); } } } catch (Exception e) { throw new RuntimeException("unexpected invocation exception: " + e.getMessage()); } return result; } } A: IMHO reflection will make your classes less readable. Also reflection is quite a bit slower then normal field or class access. As an alternative see the wrapper class approach described here: http://android-developers.blogspot.com/2009/04/backward-compatibility-for-android.html Create interface and two implementations of it, one for API 8+ and the other for the earlier versions. In your API8 class you can use API 8 classes including OnAudioFocusChangeListener. Then instantiate the version based on version of OS, which you can check via Build.VERSION.SDK_INT.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504556", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: java threads access outer class from static inner class This builds up on my previous question. My ftp server has 10 files, say test1.txt, test2.txt and so on. I want to be able to download multiple files (max 3) at the same time. I am calling downloadFilesByPattern(....) If I dont use synchronized on downloadFile() then only some of the file are downloaded not all. If I use synchronized, then all the files are downloaded, but I don't think they are happening in parallel. Is the issue because an instance varible is passed to all threads and a method on that instance is called by all threads. public class FTPClientService implements IClient { private String username; private String password; private String port; private String host; private String path; FTPClient client = new FTPClient(); private static class DownloadTask implements Runnable { private String name; private String toPath; private IClient client; public DownloadTask(String name, String toPath, IClient client) { this.name = name; this.toPath = toPath; this.client = client; } @Override public void run() { System.out.println("download = " + name); client.downloadFile(name, toPath); } } public void downloadFilesByPattern(String fileNamePattern, final String outputFilePath) { if(!changeDirectory()){ return; } try { //get a list of file names that match the pattern String[] names = client.listNames(); ExecutorService pool = Executors.newFixedThreadPool(3); for (String name : names) { //check if the filename matches the pattern Pattern pattern = Pattern.compile(fileNamePattern); Matcher matcher = pattern.matcher(name); if(matcher.find()){ System.out.println("Match found = " + name); pool.submit(new DownloadTask(name, outputFilePath, this)); }else{ System.out.println("No match = " + name); } } pool.shutdown(); try { pool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { } } catch (IOException ex) { } } public synchronized void downloadFile(String fileName, String outputFilePath) { FileOutputStream fos = null; try { fos = new FileOutputStream(outputFilePath+"/"+fileName); if(this.isFilePresent(fileName)){ //look for fileName in the path and write it to client.retrieveFile(fileName, fos); System.out.println("Downloading file " + fileName + " ..."); }else{ System.out.println("Could not find file " + fileName); } } catch (IOException ex) { } finally { try { fos.close(); } catch (IOException ex) { } } } } A: It's because they all use the same instance of FTPClient client You need to either create new instance of FTPClientService for every download/thread or have an instance of FTPClient for every thread. I personally prefer the second variant which can be easily implemented using ThreadLocal. A: FTPClient is probably not thread safe (what product is it coming from anyway?). You may want to create it right before download or create a pool of FTP clients if you need to reuse it. Also, I recommend you modify your naming convention a bit as it's very hard to distinguish in the code ftpclient vs your own client.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504557", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: session didn't started I've found an amazing problem. I today released a website which is based on MLM business. The whole day I test the website, but no errors found. But at night when I tried to login a member page I'm getting the below error: [21-Sep-2011 13:30:36] PHP Warning: session_start() [<a href='function.session-start'>function.session-start</a>]: open(/tmp/sess_44507540b8d51d06160a2856360692e6, O_RDWR) failed: Permission denied (13) in /home/dashingb/public_html/sts/conf.php on line 3 I'm on shared host with apache server. I've no root access. How to solve the problem ? also above is showing WARNING, But when I try to open the login page it shows 500 error (http://dashingbird.com/sts/admin/) my session starting method is as below: <?php if(! isset($_SESSION)){ session_start(); } ?> Plus below error is getting: Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator, webmaster@dashingbird.com and inform them of the time the error occurred, and anything you might have done that may have caused the error. More information about this error may be available in the server error log. Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request. Apache/2.0.63 (Unix) mod_ssl/2.0.63 OpenSSL/0.9.8e-fips-rhel5 mod_auth_passthrough/2.1 mod_bwlimited/1.4 FrontPage/5.0.2.2635 Server at dashingbird.com Port 80 When I turned error_reporting(E_ALL), I just got the above warning (session warning). please help me.. A: Most likely PHP can't write out the session file to whatever directory is specified for the session save path. You can find out what that path is with session_save_path(). If you can't modify the permissions on that directory to allow writes by the webserver, you'll have to change the PHP configuration to point at a directory where it CAN read/write files. Or manually override it in each script with a session_save_path('/path/to/writeable/dir') before you call session_start(). A: It seems there is something wrong on the server. Generally on a shared host there is not musc you can do yourself. I would suggest emailing (or opening a ticket) your hosting support. Its most likely some sort of permission issue. Also the 500 error means something is wrong with server config, Mostly it is caused by some error in .htaccess file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is the main window of an applet called and how do you refer to it? I'm trying to use Xoverlay and call setWindowHandle, but I need to give a component. When I do "run as applet" in eclipse, eclipse creates a small window with the appletviewer. I want to know how to get a reference to that window. I can see that they are adding elements to it here: http://download.oracle.com/javase/tutorial/deployment/applet/getStarted.html They are simply using add to add it to the main window. Right now in my application, another window is being spawned that displays video, and I want that video to be displayed in the main applet window so that I can embed the applet in an HTML page and have full control over the window. I've tried using 'root pane', but then I get this error: java.lang.IllegalArgumentException: Component must be a native window EDIT: By request, here is my code (There is a comment at the line in question): import java.applet.Applet; import java.awt.*; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.net.URI; import java.net.URISyntaxException; import javax.swing.*; import org.gstreamer.*; import org.gstreamer.elements.PlayBin2; import org.gstreamer.interfaces.XOverlay; import org.gstreamer.lowlevel.GstXOverlayAPI; public class VideoPlayer extends JApplet { public void init() { Gst.init(); final PlayBin2 playbin = new PlayBin2("VideoPlayer"); URI uri = null; try { uri = new URI("udp://239.1.1.1:51002"); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } playbin.setURI(uri); //System.setProperty("apple.awt.graphics.UseQuartz", "false"); try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { Element videosink = ElementFactory.make("xvimagesink", "imagesink"); videosink.set("qos", "false"); videosink.set("sync", "false"); playbin.setVideoSink(videosink); playbin.setState(State.PLAYING); XOverlay.wrap(videosink).setWindowHandle(rootPane); // I need the handle to the main window here } }); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } Gst.main(); playbin.setState(State.NULL); } } A: try using getRootPane() or switch from JApplet to Applet and use getParent() XOverlay.wrap(videosink).setWindowHandle(getRootPane()|getParent());
{ "language": "en", "url": "https://stackoverflow.com/questions/7504564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the role of the "Service Broker" in SOA? What is the role of the "Service Broker" in SOA Model Architecture? A: The service broker is meant to be a registry of services, and stores information about what services are available and who may use them. For example, UDDI which was originally conceived as a web service registry is now considered a SOA Service Broker. A: SOA registry is responsible for registering business services, while SOA broker is responsible for orchestrating the connections between these components.. The service broker reads the interface information from the registry and then makes the right connection to other interfaces.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504566", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: catch wrong-arguments exception, in the general case I want to catch an exception, but only if it comes from the very next level of logic. The intent is to handle errors caused by the act of calling the function with the wrong number of arguments, without masking errors generated by the function implementation. How can I implement the wrong_arguments function below? Example: try: return myfunc(*args) except TypeError, error: #possibly wrong number of arguments #we know how to proceed if the error occurred when calling myfunc(), #but we shouldn't interfere with errors in the implementation of myfunc if wrong_arguments(error, myfunc): return fixit() else: raise Addendum: There are several solutions that work nicely in the simple case, but none of the current answers will work in the real-world case of decorated functions. Consider that these are possible values of myfunc above: def decorator(func): "The most trivial (and common) decorator" def wrapper(*args, **kwargs): return func(*args, **kwargs) def myfunc1(a, b, c='ok'): return (a, b, c) myfunc2 = decorator(myfunc1) myfunc3 = decorator(myfunc2) Even the conservative look-before-you-leap method (inspecting the function argument spec) fails here, since most decorators will have an argspec of *args, **kwargs regardless of the decorated function. Exception inspection also seems unreliable, since myfunc.__name__ will be simply "wrapper" for most decorators, regardless of the core function's name. Is there any good solution if the function may or may not have decorators? A: You can do: try: myfunc() except IndexError: trace = sys.exc_info()[2] if trace.tb_next.tb_next is None: pass else: raise Although it is kinda ugly and would seem to violate encapsulation. Stylistically, wanting to catch having passed too many arguments seem strange. I suspect that a more general rethink of what you are doing may resolve the problem. But without more details I can't be sure. EDIT Possible approach: check if function you are calling has the arguments *args,**kwargs. If it does, assume its a decorator and adjust the code above to check if the exception was one further layer in. If not, check as above. Still, I think you need to rethink your solution. A: I am not a fan of doing magic this way. I suspect you have an underlying design problem rather. --original answer and code which was too unspecific to the problem removed-- Edit after understanding specific problem: from inspect import getargspec def can_call_effectively(f, args): (fargs, varargs, _kw, df) = getattr(myfunc, 'effective_argspec', \ getargspec(myfunc)) fargslen = len(fargs) argslen = len(args) minargslen = fargslen - len(df) return (varargs and argslen >= minargslen) or minargslen <= argslen <= fargslen if can_call_effectively(myfunc, args) myfunc(*args) else: fixit() All your decorators, or at least those you want to be transparent in regard to calling via the above code, need to set 'effective_argspec' on the returned callable. Very explicit, no magic. To achieve this, you could decorate your decorators with the appropriate code... Edit: more code, the decorator for transparent decorators. def transparent_decorator(decorator): def wrapper(f): wrapped = decorator(f) wrapped.__doc__ = f.__doc__ wrapped.effective_argspec = getattr(f, 'effective_argspec', getargspec(f)) return wrapped return wrapper Use this on your decorator: @transparent_decorator def decorator(func): "The most trivial (and common) decorator" def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper # line missing in example above Now if you create myfunc1 - myfunc3 as above, they work exactly as expected. A: Ugh unfortunately not really. Your best bet is to introspect the error object that is returned and see if myfunc and the number of arguments is mentioned. So you'd do something like: except TypeError, err: if err.has_some_property or 'myfunc' in str(err): fixit() raise A: you can do it by doing something like >>> def f(x,y,z): print (f(0)) >>> try: f(0) except TypeError as e: print (e.__traceback__.tb_next is None) True >>> try: f(0,1,2) except TypeError as e: print (e.__traceback__.tb_next is None) False but a better way should be to count the number of args of function and comparing with the number of args expected len(inspect.getargspec(f).args) != len (args) A: You can retrieve the traceback and look at its length. Try: import traceback as tb import sys def a(): 1/0 def b(): a() def c(): b() try: a() except: print len(tb.extract_tb(sys.exc_traceback)) try: b() except: print len(tb.extract_tb(sys.exc_traceback)) try: c() except: print len(tb.extract_tb(sys.exc_traceback)) This prints 2 3 4 A: Well-written wrappers will preserve the function name, signature, etc, of the functions they wrap; however, if you have to support wrappers that don't, or if you have situations where you want to catch an error in a wrapper (not just the final wrapped function), then there is no general solution that will work. A: I know this is an old post, but I stumbled with this question and later with a better answer. This answer depends on a new feature in python 3, Signature objects With that feature you can write: sig = inspect.signature(myfunc) try: sig.bind(*args) except TypeError: return fixit() else: f(*args) A: Seems to me what you're trying to do is exactly the problem that exceptions are supposed to solve, ie where an exception will be caught somewhere in the call stack, so that there's no need to propagate errors upwards. Instead, it sounds like you are trying to do error handling the C (non-exception handling) way, where the return value of a function indicates either no error (typically 0) or an error (non 0 value). So, I'd try just writing your function to return a value, and have the caller check for the return value.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504569", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: In ASP.NET, how can you "reset" and go back to the original state, pre postbacks? I am very new to ASP.NET. I just learned what postbacks are and I am trying to handle them, however, I would like to know if there is a way to "reset" the page. As in go to the original state of the page, before any postbacks were handled. This will clear out any text boxes, check boxes, etc. In effect clearing any and all cache. Make it look like the user just opened the page fresh for the first time. Would like it to be a button called "reset" or "Start over". A: Once you're done with your data, I would simply suggest doing a Response.Redirect("~/Example.aspx") to the same page. That way you're not passing the ViewState back to the page. Example.aspx <asp:Button id="Reset" Text="Reset" runat="server" OnClick="Reset_Click" /> Example.aspx.cs protected void Reset_Click(object sender, EventArgs e) { Session["ViewState"] = null; Response.Redirect("~/Example.aspx"); } A: In the OnClick handler of the button, you could do a Response.Redirect to the same page. A: You can use the HTML input element with a type="reset": <input type="reset" value="Reset" /> A: <asp:Button ID="Reset" runat="server" Text="Reset" align="center" onclick="Reset_Click" /> protected void Reset_Click(object sender, EventArgs e) { Session["ViewState"] = null; Response.Redirect("~/Form.aspx"); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7504570", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Strange same numbers I use some random numbers as initial values for my 'metaheuristics optimization' calculations. I run my same optimization program on different computers using MPI. I surprisingly obtained a lot of same results. For example I use 40 host computers, the results have few different values. Almost 6-7 values are the same. Actually, my results can be similar but they must not be same because I give random numbers as initials to them in the beginning of program (In my above example I must get 40 different values). If I run the program repeatedly and sequentially on a same computer, it produces different results as it should be. I suspect that this situation is caused by insufficient quality of random number generation. How can I solve this problem. I open other ideas, may be different things cause this problem. P. S. I use srand( (unsigned) time(NULL) ) once in the beginning of my program for generating random-like numbers. Then, I generate my random numbers in the range of [0, 1] by using (float)rand()/32767 One example of my results which I complained: 15.42161751 19.83328438 3.43446541 23.50453377 23.50453377 3.43446541 19.83328438 23.50453377 3.43446541 7.52127457 7.52127457 23.50453377 7.52127457 7.52127457 23.50453377 19.83328438 19.83328438 19.83328438 7.52127457 15.42161751 3.43446541 19.83328438 19.83328438 15.42161751 23.50453377 23.50453377 5.29145241 19.83328438 19.83328438 19.83328438 19.83328438 7.52127457 23.50453377 3.43446541 19.83328438 23.50453377 7.52127457 3.43446541 7.52127457 5.29145241 A: The random number generators may be receiving the same seed value. My suggestion is to create a hash of some unique identifier for the computer, computer name or MAC address, and xor that into the return from time(). A: You're correct, the default random number generator in C++ is often not very high quality. If your compiler has implemented any of C++11 you might have more choices available, see this quick reference: http://en.wikipedia.org/wiki/C%2B%2B11#Extensible_random_number_facility . If you don't have those classes available, you can find them in boost.random. You might also consider a source of true random numbers rather than the simulated pseudo-random numbers available from a library, for example the /dev/random device file on Linux. A: The quality of the random number generator is not the problem. Even the C random number generator won't produce duplicate values like you are seeing unless you are using the same seed. The function time has resolution in seconds, so it's not surprising that if you spawn several processes, the random number generators will get the same seed. You probably wanted a function like clock, which has a higher resolution. Using the clock as the seed has at least one other problem: it becomes impossible to get the same results twice from your code. A: That's because some of your host computers are having the same time, so the srand() takes the same time and therefore the random sequence have same starting point, so of course your are getting the same random numbers. Try to to this: srand(time(0)*my_computer_id); A: Use something more precise than time(NULL). I use static_cast<int64>(clock()) + time(NULL). You could also use other sources of entropy like keyboard buffer, screen buffer, memory areas, etc. Depends on the quality of randomness your application requires.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating an array with variables I am relatively new to Delphi so please bear with me. Basically, I need to set variables as different values based on whether or not I am testing in an English or French translated environment. All menus in these TC scripts are accessed by their names and in French they are not the same. I can, however, access them by their position in the menu - such as [4|2]. I have a list of constants and would like to set up an array to set MenuItem1 to either File|New or [4|2] depending on the value of tcDecimalSeparator <> '.' (set as a declared constant). Does this make sense? What would be the easiest / best way to do this? I know I could probably set this all up with data driven testing but I don't want to rework the scripts that much prior to release. A: No, your proposed solution does not make sense. First, switching based on the current decimal separator is unreliable. Second, if you already know the positions of the menu items, and they always work, regardless of the program's language, then why mess around with the English menu captions at all? Just use the menu positions all the time. (Or, if you already have something set up to select the menu text based on the language, why not also use the French menu text instead of switching between English text and French positions?) To do what you propose, you can set up a two-dimensional array of menu identifiers: const TLanguage = (lEnglish, lFrench); TUIElement = (uiFileNew, uiFileOpen, ...); MenuIDs = array[TUIElement] of array[TLanguage] of string = ( ('File|New', '[4|2]'), ('File|Open', '[4|3]') ); Then, when you want a string, select the item that corresponds to your UI element, and then select the string for the current language: if tcDecimalSeparator = '.' then CurrentLang := lEnglish else CurrentLang := lFrench; UseMenuItem(MenuIDs[uiFileNew, CurrentLang]);
{ "language": "en", "url": "https://stackoverflow.com/questions/7504575", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I use Entity Framework 4.1 with MVC 3 Login I am building my first EF 4.1 code first application in mvc3. How do I incorporate the mvc3 login with my EF4.1 classes? or maybe the question should be, how do I build the same login functionality into my EF4.1 classes? My EF classes will contain user information, which is what I want to use for the login. any suggestions are appretiated. A: Please see asp.net/mvc for a bunch of great tutorials about ASP.NET MVC. Also here is a good link on user authentication. A: As i understand from your question, you will need to implement Custom Membership Provider and override all the properties you need...refer to this article fro complete information.. http://www.mattwrock.com/post/2009/10/14/Implementing-custom-Membership-Provider-and-Role-Provider-for-Authinticating-ASPNET-MVC-Applications.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7504576", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Restrict specific date format Data into Table I Have a table called Sur_Data and the data looks like: ID SV_Date 258 13/01/2010 569 15/02/2011 695 26/05/2010 745 12/06/2010 Now I want to select the ID's from that table and insert into another table so we are using something like: Insert into Surdate(ID) Select ID from Sur_Data where ISDATE(SV_Date) = 1 Since the format in SV_Date is different it is not inserting any records into Surdate table. So I am trying to see is there a way that we could restrict the data in Sur_Data table to have only date's that are in MM/DD/YYYY format.So whenever they try to insert records of different format it should throw an error. Can anyone help on this? A: To strictly answer the question, you could create a function (CLR or TSQL) and apply that as a column constraint/check. But as @joe Stefanelli correctly points out, store it as a datetime data type and let the client handle the presentation format. Edit http://msdn.microsoft.com/en-us/library/ms190273.aspx ALTER TABLE dbo.Sur_Data WITH CHECK ADD CONSTRAINT ck_dateFormatted CHECK (dbo.VerifyDateFormat(SV_Date) = 1) ; Which assumes you've defined a function that returns 1 if the format matches the expectation. A: Edit: for example 2 & 3, ANSI WARNINGS must be off. IS_DATE function is influenced by DATEFORMAT setting for current SQL Server session/connection. Example 1: DECLARE @d1 VARCHAR(25) = '26/05/2010' ,@d2 VARCHAR(25) = '15/02/2011'; PRINT '*****Test 1*****' SET DATEFORMAT DMY; SELECT ISDATE(@d1), ISDATE(@d2); PRINT '*****Test 2*****' SET DATEFORMAT MDY; SELECT ISDATE(@d1), ISDATE(@d2); Results: *****Test 1***** ----------- ----------- 1 1 (1 row(s) affected) *****Test 2***** ----------- ----------- 0 0 (1 row(s) affected) Now, you can see how DATEFORMAT influences ISDATE function. Instead of ISDATE function you can use CONVERT function with different date/time styles. If a [n][var]char value doesn't have the selected style then CONVERT function will return NULL. For dd/mm/yyyy values (british) can be used style 103 and for mm/dd/yyyy values (U.S.) can be used style 101. Example 2: SET ANSI_WARNINGS OFF; SET ARITHABORT OFF; DECLARE @Results TABLE ( ID INT PRIMARY KEY ,SV_Date VARCHAR(20) NOT NULL ); INSERT @Results VALUES (258, '13/01/2010') ,(569, '15/02/2011') ,(695, '26/05/2010') ,(745, '12/06/2010'); SELECT * ,ISDATE(r.SV_Date) [IS_DATETIME] ,CONVERT(DATETIME,r.SV_Date,103) [IS_DATETIME British/French style=dd/mm/yyyy] ,CONVERT(DATETIME,r.SV_Date,101) [IS_DATETIME U.S. style=mm/dd/yyyy] ,CASE WHEN CONVERT(DATETIME,r.SV_Date,103) IS NOT NULL AND CONVERT(DATETIME,r.SV_Date,101) IS NULL THEN 'IS_DMY' WHEN CONVERT(DATETIME,r.SV_Date,103) IS NULL AND CONVERT(DATETIME,r.SV_Date,101) IS NOT NULL THEN 'IS_MDY' WHEN CONVERT(DATETIME,r.SV_Date,103) IS NOT NULL AND CONVERT(DATETIME,r.SV_Date,101) IS NOT NULL THEN 'IS_DMY_OR_MDY' WHEN CONVERT(DATETIME,r.SV_Date,103) IS NULL AND CONVERT(DATETIME,r.SV_Date,101) IS NULL THEN 'IS_NOT_DMY_OR_MDY' END FROM @Results r; Results: ID SV_Date IS_DATETIME IS_DATETIME British/French style=dd/mm/yyyy IS_DATETIME U.S. style=mm/dd/yyyy ----------- -------------------- ----------- ------------------------------------------- --------------------------------- ----------------- 258 13/01/2010 0 2010-01-13 00:00:00.000 NULL IS_DMY 569 15/02/2011 0 2011-02-15 00:00:00.000 NULL IS_DMY 695 26/05/2010 0 2010-05-26 00:00:00.000 NULL IS_DMY 745 12/06/2010 1 2010-06-12 00:00:00.000 2010-12-06 00:00:00.000 IS_DMY_OR_MDY Now, if you want to check SV_Date values for mm/dd/yyyy format (style 101 - U.S.) then you can use a CHECK constraint like this: Example 3: DECLARE @Results2 TABLE ( ID INT PRIMARY KEY ,SV_Date VARCHAR(20) NOT NULL ,CHECK( CONVERT(DATETIME,SV_Date,101) IS NOT NULL ) ); SET ANSI_WARNINGS OFF; INSERT @Results2 VALUES (258, '13/01/2010'); INSERT @Results2 VALUES (569, '15/02/2011'); INSERT @Results2 VALUES (695, '26/05/2010'); INSERT @Results2 VALUES (745, '12/06/2010'); SELECT * FROM @Results2; Results: ID SV_Date ----------- -------------------- 745 12/06/2010 (1 row(s) affected) Observations: If you want to find current DATEFORMAT setting (current session) then you can use sys.dm_exec_sessions view: SELECT s.date_format, s.date_first FROM sys.dm_exec_sessions s WHERE s.session_id = @@SPID
{ "language": "en", "url": "https://stackoverflow.com/questions/7504584", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Left join, how to specify 1 result from the right? This one is fairly specific, so I'm hoping for a quick fix. I have a single result in my leaderboard table for each team. In my teams table, I have several results for each team (one result per game to enable team development history). I want to show each team in the leaderboard once, and have teamID replaced by strName. Problem is, my left join is giving me one record for each team result; I just want a single record. SELECT * , a.strName AS teamName FROM bb_leaderboards l LEFT JOIN bb_teams a ON ( l.teamID = a.ID ) WHERE l.season =8 AND l.division =1 ORDER BY l.division DESC , points DESC , wins DESC , l.TDdiff DESC LIMIT 0 , 30 What do I need to do to this to get a 1:1 output? A: You could do a SELECT DISTINCT instead, but you'll have to narrow down your select a bit. So: SELECT DISTINCT l.*, a.strName AS teamName ... That should filter out the duplicates.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Unable to bind data to an autocomplete box in a silverlight 4 datagrid I'm new to silverlight and I'm tasked with changing the datagrid TextColumns to autocomplete boxes. I thought this should be fairly simple but apparently it isn't. I'm able to bind the data from a list outside the datagrid but not from within. I've been researching for two days now and everything I find seems to incorporate data from a database or is otherwise too complex for my newbie brain to figure out. All I really need is a simple example and explanation of how to do this in a datagrid as opposed to regularly. My code follows. It builds succesfully but does not work properly. I'm sure this is a problem that many others must have come across. I appreciate anyone's input, Thanks in advance. d. <UserControl xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk" xmlns:toolkit="http://schemas.microsoft.com/winfx/2006/xaml/presentation/toolkit" x:Class="AccordionAutoCompleteBox.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" d:DesignHeight="680" d:DesignWidth="1240"> <Grid x:Name="LayoutRoot" Background="White"> <StackPanel VerticalAlignment="Center"> <toolkit:AccordionItem x:Name="AccordionItem2" FontSize="12" Background="LightBlue" BorderBrush="Wheat" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" IsSelected="False" MaxHeight="400"> <sdk:DataGrid Name="AccordionGrid" ItemsSource="{Binding ExpData}" AutoGenerateColumns="False" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" HeadersVisibility="All" BorderThickness="1" Margin="8" SelectionMode="Single" Canvas.ZIndex="-1" MaxHeight="360"> <sdk:DataGrid.Columns> <sdk:DataGridTemplateColumn Header="Exp"> <sdk:DataGridTemplateColumn.CellTemplate> <DataTemplate> <sdk:AutoCompleteBox x:Name="AutoCompGrid" Text="{Binding Exp, Mode=TwoWay}" ItemsSource="{Binding Exp}" IsTextCompletionEnabled="True" /> </DataTemplate> </sdk:DataGridTemplateColumn.CellTemplate> </sdk:DataGridTemplateColumn> <sdk:DataGridTextColumn Header="Exp" Binding="{Binding Exp}" IsReadOnly="False" /> <sdk:DataGridTextColumn Header="Desc" Binding="{Binding Desc}" IsReadOnly="False" /> <sdk:DataGridTextColumn Header="Prod" Binding="{Binding Prod}" IsReadOnly="False" /> <sdk:DataGridTextColumn Header="Source" Binding="{Binding Source}" IsReadOnly="False" /> <sdk:DataGridTextColumn Header="Start" Binding="{Binding Start}" IsReadOnly="False" /> <sdk:DataGridTextColumn Header="Reset" Binding="{Binding Reset}" IsReadOnly="False" /> <sdk:DataGridTextColumn Header="Amt" Binding="{Binding Amt}" IsReadOnly="False" /> </sdk:DataGrid.Columns> </sdk:DataGrid> </toolkit:AccordionItem> <sdk:AutoCompleteBox x:Name="AutoCompGrid2" Text="{Binding Exp}" ItemsSource="{Binding Exp}" IsTextCompletionEnabled="False" /> </StackPanel> </Grid> And the code behind namespace AccordionAutoCompleteBox { public partial class MainPage : UserControl { public MainPage() { InitializeComponent(); List<ExpData> myList = new List<ExpData> { new ExpData {Exp = "cell 1", Desc = "cell 2", Prod = "cell 3", Source = "cell 4", Start = "cell 5", Amt = "cell 6", Reset = "cell 7"}, new ExpData {Exp = "cell 8", Desc = "cell 9", Prod = "cell 10", Source = "cell 11", Start = "cell 12", Amt = "cell 13", Reset = "cell 14"} }; AccordionGrid.ItemsSource = myList; AutoCompGrid2.ItemsSource = myList; this.AccordionItem2.Header = " Accordion Header "; } } public class ExpData { public String Exp { get; set; } public String Desc { get; set; } public String Prod { get; set; } public String Source { get; set; } public String Start { get; set; } public String Reset { get; set; } public String Amt { get; set; } public ExpData(String exp, string desc, string prod, string source, string start, String reset, String amt) { Exp = exp; Desc = desc; Prod = prod; Source = source; Start = start; Reset = reset; Amt = amt; } public override string ToString() { return Exp; } A: Your life would be a lot easier if you had a view model. :) Quick example of using a ViewModel to solve this. public class ExpDataViewModel { private List<ExpData> _listData; public ExpDataViewModel() { _listData = new List<ExpData> { new ExpData {Exp = "cell 1", Desc = "cell 2", Prod = "cell 3", Source = "cell 4", Start = "cell 5", Amt = "cell 6", Reset = "cell 7"}, new ExpData {Exp = "cell 8", Desc = "cell 9", Prod = "cell 10", Source = "cell 11", Start = "cell 12", Amt = "cell 13", Reset = "cell 14"} }; } public IEnumerable<ExpData> ListData { get {return _listData;} } public IEnumerable<string> ExpItems { get {return _listData.Select(i => i.Exp); } } Then you would need to change your view: <UserControl xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk" xmlns:toolkit="http://schemas.microsoft.com/winfx/2006/xaml/presentation/toolkit" x:Class="AccordionAutoCompleteBox.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:vm="[Your ViewModel's Namespace]" mc:Ignorable="d" d:DesignHeight="680" d:DesignWidth="1240"> <UserControl.Resources> <vm:ExpDataViewModel x:Key="vm" /> </UserControl.Resource> <Grid x:Name="LayoutRoot" Background="White" DataContext="{StaticResource vm}"> <StackPanel VerticalAlignment="Center"> <toolkit:AccordionItem x:Name="AccordionItem2" FontSize="12" Background="LightBlue" BorderBrush="Wheat" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" IsSelected="False" MaxHeight="400"> <sdk:DataGrid Name="AccordionGrid" ItemsSource="{Binding ListData}" AutoGenerateColumns="False" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" HeadersVisibility="All" BorderThickness="1" Margin="8" SelectionMode="Single" Canvas.ZIndex="-1" MaxHeight="360"> <sdk:DataGrid.Columns> <sdk:DataGridTemplateColumn Header="Exp"> <sdk:DataGridTemplateColumn.CellTemplate> <DataTemplate> <sdk:AutoCompleteBox x:Name="AutoCompGrid" Text="{Binding Exp, Mode=TwoWay}" ItemsSource="{Binding Path=ExpItems, Source={StaticResource vm}}" IsTextCompletionEnabled="True" /> </DataTemplate> </sdk:DataGridTemplateColumn.CellTemplate> </sdk:DataGridTemplateColumn> <sdk:DataGridTextColumn Header="Exp" Binding="{Binding Exp}" IsReadOnly="False" /> <sdk:DataGridTextColumn Header="Desc" Binding="{Binding Desc}" IsReadOnly="False" /> <sdk:DataGridTextColumn Header="Prod" Binding="{Binding Prod}" IsReadOnly="False" /> <sdk:DataGridTextColumn Header="Source" Binding="{Binding Source}" IsReadOnly="False" /> <sdk:DataGridTextColumn Header="Start" Binding="{Binding Start}" IsReadOnly="False" /> <sdk:DataGridTextColumn Header="Reset" Binding="{Binding Reset}" IsReadOnly="False" /> <sdk:DataGridTextColumn Header="Amt" Binding="{Binding Amt}" IsReadOnly="False" /> </sdk:DataGrid.Columns> </sdk:DataGrid> </toolkit:AccordionItem> <!-- not sure what this is supposed to be bound to --> <sdk:AutoCompleteBox x:Name="AutoCompGrid2" Text="{Binding Exp}" ItemsSource="{Binding Exp}" IsTextCompletionEnabled="False" /> </StackPanel> </Grid> And you can remove all your custom code from the code behind file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504591", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why do I get "Usage: JSON::XS::new(klass)" error? This line my $json = new JSON(autoconv => 0); # <-- line X raises this error Usage: JSON::XS::new(klass) at (...) line X What's wrong? It's a follow up to my question Is there a way to force quotation of numbers in JSON 1.x Perl module? A: The API for the JSON module changed substantially between 1.15 and 2.00. Code written for JSON 1.x won't necessarily work with JSON 2.x. In particular, the 1.x constructor took optional parameters. The 2.x constructor takes no parameters; instead, you use mutator functions after construction. If you must support both JSON 1.x and 2.x for some reason, you'll need to check if JSON->VERSION < 2 (actually JSON->VERSION < 1.99 if you count the development releases of the 2.x API) and have two versions of your code, one for the 1.x API and one for 2.x. A: Try: my $json = JSON::XS->new; I don't see any autoconv anywhere in either JSON or JSON::XS, but JSON does say this: $JSON::AUTOCONVERT Needless. JSON backend modules have the round-trip integrity.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504592", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android - Best way to overlay a play button on an image/thumbnail I have an android application which can playback audio/video and show pictures. For videos I want to overlay a play button on top of the preview image and also in list views.. Right now how I'm doing it is with an ImageView in xml, and then the drawable is a layer layer-list which I define programmatically because one of the images is dynamic, the play button is static of course. I want to align the play button 10px from the bottom, and centered horizontally. My ImageView is defined like this (in xml) <ImageView android:id="@+id/EvidencePreview" android:layout_width="267dp" android:layout_height="201dp" android:scaleType="centerCrop" android:layout_margin="3dp" android:layout_gravity="center_horizontal|center_vertical"/> The ImageView is part of a form where the user can edit title and other information. Then in my activity now I create the layer list like this: Resources resources = mContext.getResources(); Drawable playOverlayDrawable = resources.getDrawable(R.drawable.play_overlay_large); Drawable[] layers = new Drawable[2]; layers[0] = Drawable.createFromPath(tb.filePath); layers[1] = playOverlayDrawable; LayerDrawable layerDrawable = new LayerDrawable(layers); ViewGroup.LayoutParams lp = iv.getLayoutParams(); int imageHeight = lp.height; int imageWidth = lp.width; int overlayHeight = layers[1].getIntrinsicHeight(); int overlayWidth = layers[1].getIntrinsicWidth(); int lR = (imageWidth - overlayWidth) / 2; int top = imageHeight - (overlayHeight + 10); int bottom = 10; layerDrawable.setLayerInset(1, lR, top, lR, bottom); iv.setImageDrawable(layerDrawable); This only works when the orientation of the image is horizontal. Keep in mind that the image/thumbnail is the MINI_KIND which means its supposed to be 512 x 384 but I'm seeing that it actually isn't the size.. On my phone they are either 480x800 or 800x480 depending on the orientation the camera was in.. Since my layout width/height is pre defined I just want a way to keep the play button layer from scaling at all and align it the same way everytime.. The other obvious way to do this would be to use a relative layout (or perhaps a frame layout?) but I was hoping to avoid that since I'm using the same code for displaying both images and videos (both of which have an image thumbnail preview -- but only videos should have the play button on them). Any idea how to align the layers with a layer list, or alternatives that would work just as well or better? A: I ended up using a FrameLayout like this: <FrameLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="3dp" android:layout_gravity="center_horizontal|center_vertical" > <ImageView android:id="@+id/MediaPreview" android:layout_width="267dp" android:layout_height="201dp" android:scaleType="centerCrop" android:src="@drawable/loading" /> <ImageView android:id="@+id/VideoPreviewPlayButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingBottom="10dp" android:layout_gravity="center_horizontal|bottom" android:visibility="gone" android:src="@drawable/play_overlay_large" /> </FrameLayout> Then I just set the visibility to View.VISIBLE to the preview play button for videos and left it gone for photos. For my list view I used the layer list method shown above because all of the thumbnails were the same dimension. Hope this helps someone else! notice that the layout_gravity on the ImageView with id VideoPreviewPlayButton puts it at the bottom centered horizontally, and the 10dp paddingBottom moves it up a bit from the bottom. A: Consider using RelativeLayout as the container for your views. It gives you freedom of placing child views. You could bind your button to the right or top edge of your imageview.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504593", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: MVC3 - File Download - Wait Status indicator Ok, I've done my homework and have found similar threads. However, I haven't found a good answer. Using MVC3, C#, Razor View Engine. My scenario is pretty straightforward. I have a view with a link that calls an action on a controller. That action returns a file that was dynamically generated. The process takes anywhere from 1 to 10 seconds. During this time I want to lock the UI and display a "Please Waite" message. My first attempt used something like this: @Ajax.ActionLink("my test link", "myAction", new { Controller = "myController" }, new AjaxOptions { OnBegin = "ajaxStart", OnComplete = "ajaxStop" }) The ajaxStart and ajaxStop functions then used the jquery blockUI script to block and unblock the UI and display the "Please Wait" message. This worked in that it showed the message, but no file would download. After some more research, I found that I could not use Ajax to initiate a file download. If I'm wrong, please enlighten me. So, I'm back to a normal ActionLink. This works in that I can download a file. I can even catch the .click event and block the UI and show the wait message. However, how do I know when to unblock the UI? How can I know when the file save/open dialog has opened up? Perhaps if I could catch that event I could then unblock the UI. I have seen the other posts that recommend a much more complex solution by breaking the file generation/download into separate functionality. I very much want to avoid having to save the file on the server, or having to poll the server to see if the file is done yet. This should be fairly simple. If anyone has any ideas, please let me know. Thanks, Tony A: there was a post awhile back on this on SO: Detect when browser receives file download It referenced this link: http://geekswithblogs.net/GruffCode/archive/2010/10/28/detecting-the-file-download-dialog-in-the-browser.aspx Effectively what it does is it sends a cookie (C# Generated) with the file (that the user is downloading) to the client. Once the client has the cookie, theoretically this happens after the file is downloaded). Javascript will check to see if the client has that cookie, if so Javascript will unblock the UI.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504596", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: should I use "query" + "update/insert" or "insert/replace" in android sqlite? I have a table like this db.execSQL("CREATE TABLE " + TABLE_NAME + " (" + _ID + " INTEGER PRIMARY KEY," + URL + " TEXT UNIQUE," + SomeInfo + " TEXT," + OtherInfo + " INTEGER" + ");"); So there is only one record for each URL value. When the user visit a URL, I need neither insert a new row, or update an existing row if URL is presented I could think of 2 ways: * *SQLiteDatabase.query first and apply an update if there is one *Always use SQLiteDatabase.replace, in case the UNIQUE constraint fail, sqlite will replace the record. Which approach is better? Are there other suggestions? Thanks A: Since this seems to be a commom issue (which I faced recently too) I found this post which might be helpful.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504600", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Best solution to transcode mp3s (lower bitrate) and stream on the fly I have a large repo of mp3s on my LAMP server (I think it's a Debian VPS now) and currently I use a crude flash based mp3 player that "streams" the mp3s directly from my server. I am implementing an HTML5 player but I feel this is a similar to my flash integration (and this is slightly besides the point of this question) This question is about how I should start molding my delivery to limit bandwidth - connection speed isn't entirely an issue (although should be reasonable) but my bandwidth costs are flying now and I need to take measures to limit stream quality (transcode down to 128) Ideally I'd like to avoid RTMP so I can use my shiny new soundmanager2(html5) plugin for mobile etc, and as such I've been looking into this article here - http://www.metabrew.com/article/transcoding-http-mp3-streaming-proxy-in-bash which details how to create a proxy to on-the-fly transcode bitrate and serve new files. I am fairly new to this arena and am open to all solutions! Thanks! P.S I am open to 3rd party services - affordable ones at least :) Possible Solutions (on SO) * *reduce bandwidth streaming mp3s php
{ "language": "en", "url": "https://stackoverflow.com/questions/7504606", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Using select enum variable, will it cause an error that the compiler will detect? VB6 In this scenario, What would happen? Would the compiler see an error or would it go undetected? Or would it even cause an error? What should I expect the behavior to be using a select like this? enum Age over18 = 19 under18 = 17 end enum ... ... Dim myAge As Age Select case myAge case over18 ... case under18 ... End Select Thanks for the help A: I haven't tested it, but I would have thought your code would be fine. The variable myAge could be set to either over18 or under18 and then the select statement will choose the appropriate branch based on the variable's value. The compiler shouldn't care that that your enum names do not correspond to the values you have assigned to them, your code maybe confusing for anyone who tried to maintain it in the future though. A: I second ipr101's answer, but note that VB doesn't magically know that the under18 enum value should match anything less than 18 so you'd need to check for 0 to 18. Select case myAge case over18 to 999 ... case 0 to under18 ... End Select This also means that it no longer fits an enum and a select case structure so a normal If would better suit.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504614", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to "embed" Piecewise in NDSolve in Mathematica * *I am using NDSolve to solve a non-linear partial differential equation. *I'd like one of the variables (Kvar) to be a function of the time step currently being solved and hence and using Piecewise. *Mathematica generates an error message saying: SetDelayed::write: Tag Real in 0.05[t_] is Protected. >> NDSolve::deqn: Equation or list of equations expected instead of $Failed in the first argument .... ReplaceAll::reps: .... I haven't included the entire error message for ease of reading. My code is as follows: Needs["VectorAnalysis`"] Needs["DifferentialEquations`InterpolatingFunctionAnatomy`"]; Clear[Eq4, EvapThickFilm, h, S, G, E1, K1, D1, VR, M, R] Eq4[h_, {S_, G_, E1_, K1_, D1_, VR_, M_, R_}] := \!\( \*SubscriptBox[\(\[PartialD]\), \(t\)]h\) + Div[-h^3 G Grad[h] + h^3 S Grad[Laplacian[h]] + (VR E1^2 h^3)/(D1 (h + K1)^3) Grad[h] + M (h/(1 + h))^2 Grad[h]] + E1/( h + K1) + (R/6) D[D[(h^2/(1 + h)), x] h^3, x] == 0; SetCoordinates[Cartesian[x, y, z]]; EvapThickFilm[S_, G_, E1_, K1_, D1_, VR_, M_, R_] := Eq4[h[x, y, t], {S, G, E1, K1, D1, VR, M, R}]; TraditionalForm[EvapThickFilm[S, G, E1, K1, D1, VR, M, R]]; And the second cell where I am trying to implement Piecewise in NDSolve: L = 318; TMax = 7.0; Off[NDSolve::mxsst]; (*Ktemp = Array[0.001+0.001#^2&,13]*) hSol = h /. NDSolve[{ (*S,G,E,K,D,VR,M*) Kvar[t_] := Piecewise[{{0.01, t <= 4}, {0.05, t > 4}}], EvapThickFilm[1, 3, 0.1, Kvar[t], 0.01, 0.1, 0, 160], h[0, y, t] == h[L, y, t], h[x, 0, t] == h[x, L, t], (*h[x,y,0] == 1.1+Cos[x] Sin[2y] *) h[x, y, 0] == 1 + (-0.25 Cos[2 \[Pi] x/L] - 0.25 Sin[2 \[Pi] x/L]) Cos[ 2 \[Pi] y/L] }, h, {x, 0, L}, {y, 0, L}, {t, 0, TMax} ][[1]] hGrid = InterpolatingFunctionGrid[hSol]; PS: I am sorry but the first cell block doesn't display so well here. And thanks to not having enough "reputation", I can't post images. The error message occurs when using the NDSolve cell block. A: Define the function Kvar outside of a set of equations in NDSolve, like Off[NDSolve::mxsst]; (*Ktemp=Array[0.001+0.001#^2&,13]*) Kvar[t_] := Piecewise[{{0.01, t <= 4}, {0.05, t > 4}}]; hSol = ... and remove it from the list in NDSolve, so that it starts as NDSolve[{(*S,G,E,K,D,VR,M*)EvapThickFilm[..., and it will work. It gives warnings, but those are related to possible singularities in your equation. Also, your original error indicates that your Kvar was assigned a value of 0.05. So, add Clear[Kvar] before anything else in the second cell.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504616", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why does this override of a generic method work with 1.6, but not 1.7? Given the following class, which overrides the getListeners method from AbstractListModel: import java.util.EventListener; import javax.swing.AbstractListModel; public class GenericBug extends AbstractListModel { /** * This is the method of interest * This is the exact same method signature that is present in the base class */ @Override public <T extends EventListener> T[] getListeners(Class<T> listenerType) { // do something useful here... return super.getListeners(listenerType); } // Not important here @Override public int getSize() { return 0; } @Override public Object getElementAt(int index) { return null; } } This class compiles fine using an Oracle 1.6 JDK. Trying the exact same class using an Oracle 1.7 JDK, I get compile errors saying there is a name clash, but the method isn't overridden (but it is!!) Here is the error I get when I use JDK7: % /usr/java/jdk1.7.0/bin/javac GenericBug.java GenericBug.java:10: error: name clash: <T#1>getListeners(Class<T#1>) in GenericBug and <T#2>getListeners(Class<T#2>) in AbstractListModel have the same erasure, yet neither overrides the other public <T extends EventListener> T[] getListeners(Class<T> listenerType) { ^ where T#1,T#2 are type-variables: T#1 extends EventListener declared in method <T#1>getListeners(Class<T#1>) T#2 extends EventListener declared in method <T#2>getListeners(Class<T#2>) GenericBug.java:12: error: incompatible types return super.getListeners(listenerType); ^ required: T[] found: EventListener[] where T is a type-variable: T extends EventListener declared in method <T>getListeners(Class<T>) GenericBug.java:9: error: method does not override or implement a method from a supertype @Override ^ Note: GenericBug.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. 3 errors Can someone explain to me what is happening? Is this a compiler bug in JDK1.7, or am I missing something? A: First of all, AbstractListModel is generic, you should not inherit it raw. If class GenericBug extends AbstractListModel<Something> the code compiles. Now it is inherited raw, so what's happening? A raw type's instance methods all undergo erasure too [4.8], so the raw AbstractListModel has a method public EventListener[] getListeners(Class listenerType) The GenericBug.getListeners method in the subclass does not override this method[8.4.8.1]. This is based on JLS3, which Javac 6 should follow. So it must have been a Javac6 bug. It appears that javac 7 has rewritten the type system algorithms, with a much better result. JSL3: http://java.sun.com/docs/books/jls/third_edition/html/j3TOC.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7504617", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: jQuery UI autosuggest search box with results presented in similar format to linkedin's search I'm trying to create an autosuggest search box using jQuery UI and I would like it if I could present the results similarly to how linked-in presents theirs within groups (screenshot attached). Does anyone know how this might be accomplished? A: There is an example here which may help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504619", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Windows Phone ListPicker in fullscreen mode does not show item value I've just started with WP 7.1. I tried the C# LocalDatabaseSample on msdn (http://msdn.microsoft.com/en-us/library/hh286405%28v=vs.92%29.aspx). I tried to modify the Listpicker (in the AddNewItem sreen) to let the user choose an item from a list. It works well when there are 3 items in the list. However, when there are about 30 items, the Listpicker goes to fullscreen mode, and it does not show the item value, but something like "LocalDatabaseSample.Model.ToDoCategory". How do I fix this? Thanks. A: You should look at retemplating the FullModeItemTemplate for the listpicker and/or overriding ToString on your model.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504621", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Obtain volume help How can I get a pointer to VolumeDeviceObject? http://msdn.microsoft.com/en-us/library/windows/hardware/ff563030(v=vs.85).aspx NTSTATUS RtlVolumeDeviceToDosName( __in PVOID VolumeDeviceObject, __out PUNICODE_STRING DosName ); VolumeDeviceObject [in] Pointer to a device object that represents a volume device object created by a storage class driver. A: You can try using IoGetDeviceObjectPointer. It returns a device object for the specified string.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I add multiple pictures from database to a report "detail"? I'm building a report in iReport so I can generate PDFs from my db data. Along with my "description" field I have multiple images which I'd like to display in the detail band. The amount of pictures depends on the exact report I'm generating the PDF for. What is the best approach for display these images? I'd like them displayed one under the other with their appropriate captions. The filename/locations are store in a "pictures" table along with the captions. I assume I need a subreport? A: You can use imageExpression property to managing WHAT picture to display. For example: <parameter name="whatImageToShow" class="java.lang.Integer" isForPrompting="true"> <defaultValueExpression><![CDATA[Integer.valueOf(1)]]></defaultValueExpression> </parameter> ... <image> <reportElement x="0" y="296" width="270" height="65"/> <imageExpression><![CDATA[$P{whatImageToShow}.intValue() == 0 ? "image1.jpg" : "image2.png"]]></imageExpression> </image> With help of printWhenExpression property you can manage WHEN you need to show image. For example: <parameter name="toShowPicture" class="java.lang.Boolean" isForPrompting="true"> <defaultValueExpression><![CDATA[CDATA[Boolean.valueOf(false)]]></defaultValueExpression> </parameter> ... <image> <reportElement x="0" y="296" width="270" height="65"> <printWhenExpression><![CDATA[$P{toShowPicture}.booleanValue()]]></printWhenExpression> </reportElement> <imageExpression><![CDATA[$P{whatImageToShow}.intValue() == 0 ? "image3.jpg" : "image4.png"]]></imageExpression> </image> The filename/locations are store in a "pictures" table along with the captions. I assume I need a subreport? Yes, you cannot use several queries (datasources) in one report. And yes, you need a subreport. You can return data from subreport to master data. You can view sample report at $IREPORT_HOME$\ireport\samples\Subreports folder and read this case. UPDATED: I've just found useful as I think article Creating jasper reports with dynamic images. May be it helps you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504627", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: trying to override dependency of Apache Tika 0.9 from PDFBOX 1.4.0 to PDFBOX 1.6.0 <dependency> <groupId>org.apache.tika</groupId> <artifactId>tika-parsers</artifactId> <version>0.9</version> </dependency> I was trying to add this below dependency instead of just above dependency of tika to override the dependency of Tika to PDFBOX 1.6.0 But its not working.. <dependency> <groupId>org.apache.tika</groupId> <artifactId>tika-parsers</artifactId> <version>0.9</version> <exclusions> <exclusion> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>1.6.0</version> </dependency> Tika Parser has a dependency on PdfBox version 1.4.0. And I wanted to change this dependency of Apache Tika to PdfBox version 1.6.0. How can I do this in my Pom.xml file. This is my pom.xml file. Any suggestions will be appreciated. < project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.xyz.search</groupId> <artifactId>xyzz-crawler4j</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>qcom-crawler4j</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <repositories> <repository> <id>repo-for-dsiutils</id> <url>http://ir.dcs.gla.ac.uk/~bpiwowar/maven/</url> </repository> <repository> <id>JBoss</id> <name>jboss-maven2-release-repository</name> <url>https://oss.sonatype.org/content/repositories/JBoss</url> </repository> <repository> <id>oracle</id> <url>http://download.oracle.com/maven</url> </repository> <repository> <id>boilerpipe</id> <url>http://boilerpipe.googlecode.com/svn/repo/</url> </repository> </repositories> <dependencies> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.0.1</version> <!-- 4.1.1 --> </dependency> //PDFBOX version 1.6.0 <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>1.6.0</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> <version>4.0.1</version> </dependency> <!-- 4.1 --> <dependency> <groupId>it.unimi.dsi</groupId> <artifactId>fastutil</artifactId> <version>6.2.2</version> </dependency> <dependency> <groupId>com.sleepycat</groupId> <artifactId>je</artifactId> <version>4.0.71</version> </dependency> <!-- Boilerpipe --> <dependency> <groupId>de.l3s.boilerpipe</groupId> <artifactId>boilerpipe</artifactId> <version>1.2.0</version> </dependency> <!-- Tika (for non-HTML extractions) --> <dependency> <groupId>org.apache.tika</groupId> <artifactId>tika-core</artifactId> <version>0.9</version> </dependency> <dependency> <groupId>xerces</groupId> <artifactId>xercesImpl</artifactId> <version>2.8.1</version> </dependency> <dependency> <groupId>nekohtml</groupId> <artifactId>nekohtml</artifactId> <version>0.6.5</version> </dependency> <dependency> <groupId>org.apache.tika</groupId> <artifactId>tika-parsers</artifactId> <version>0.9</version> </dependency> **// I was trying to add this below dependency instead of just above dependency of tika to override the dependency of Tika to PDFBOX 1.6.0 But its not working.. <!-- <dependency> <groupId>org.apache.tika</groupId> <artifactId>tika-parsers</artifactId> <version>0.9</version> <exclusions> <exclusion> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>1.6.0</version> </dependency> -->** </dependencies> </project> A: The cleanest approach is probably to add a dependencyManagement section that upgrades the PDFBox version within your dependency tree. For example: <dependencyManagement> <dependencies> <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>1.6.0</version> </dependency> </dependencies> </dependencyManagement> Note that many Tika parsers are tightly tied to specific versions of the upstream parser libraries like PDFBox, so you'll need to test the system well if you override the dependency versions like this. An alternative to forcing a dependency version change is to use the latest trunk version of Tika where the PDFBox dependency is already at version 1.6.0. Also, the Tika 0.10 release that will use the updated dependency should be out already early next week.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Java input without pausing How would I make a sort of console for my program without pausing my code? I have a loop, for example, that needs to stay running, but when I enter a command in the console, I want the game to check what that command was and process it in the loop. The loop shouldn't wait for a command but just have an if statement to check if there's a command in the queue. I'm making a dedicated server, by the way, if that helps. A: There's pretty obvious approach: use a dedicated thread to wait on InputStream, read events/commands from it and pass them into a queue. And your main thread will be regularly checking this queue. After every check it will either process a command from the queue or continue what it was doing if it's empty. A: What you'd like to have is a thread in which you keep the command reading code running. It'd probably look something like this: class ReadCommand implements Runnable { public void run() { // Command reading logic goes here } } In your "main" thread where the rest of the code is running, you'll have to start it like this: new Thread(new ReadCommand())).start() Additionally, you need a queue of commands somewhere which is filled from ReadCommand and read from the other code. I recommend you to read a manual on concurrent java programming. A: Have them run in two separate threads. class Server { public static void main(String[] args) { InputThread background = new InputThread(this).start(); // Run your server here } } class InputThread { private final Server server; public InputThread(Server server) { this.server = server; } public void run() { Scanner sc = new Scanner(System.in); while(sc.hasNextLine()) { // blocks for input, but won't block the server's thread } } } A: The server should run in its own thread. This will allow the loop to run without pausing. You can use a queue to pass commands into the server. Each time through the loop the server can check the queue and process one or more commands. The command line can then submit commands into the queue according to its own schedule. A: You can read from the console in a separate thread. This means your main thread doesn't have to wait for the console. Even server applications can have a Swing GUI. ;)
{ "language": "en", "url": "https://stackoverflow.com/questions/7504641", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: GWT compiler doesn't create symbolMaps in the right place I recently integrated gwt-log into my GWT and Maven based project mostly because of it's ability to automatically deobfuscate client side stack traces on the server. To make this possible gwt-log needs a so called symbol-map which maps all of the obfuscated symbol names to the original Java symbol names. The GWT compiler is capable of generating these symbol maps but for some reason they are saved to a strange location, eg.: target/project-name-1.0-SNAPSHOT/project-name/.junit_symbolMaps/0F9FD6EF6A1BC63EA834AC33C7ED13F3.symbolMap According to the GWT Maven Plugin Documentation the GWT compiler has a "-deploy" parameter which determines where to create files like that and which per default points to "WEB-INF/deploy". But even if I manually set this parameter to the correct location the compiler still creates the symbol-maps in the wrong folder. I even downloaded the GWT Maven Plugin sources and added some log output to find out whether or not the "-deploy" parameter is passed correctly to the compiler but all seems fine. Has anybody experienced a similar behavior? Thanks! Michael A: Disable JUnit GWT Module. http://groups.google.com/group/google-web-toolkit/browse_thread/thread/552a9578a76587ae#
{ "language": "en", "url": "https://stackoverflow.com/questions/7504644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Visual C++ Volatile The MSDN docs for "volatile" in Visual C++ indicate that writes have "release semantics" and that reads have "acquire semantics", in addition to ensuring that reads always read from memory and that writes always write accordingly. The C spec for "volatile" includes the second part (don't do crazy optimizations), but not the first part (a memory fence). Is there any way in Visual C++ to get the "C" volatile behaviour only, without the memory fence? I want to force a variable to always be on the stack, in a fixed spot, but I don't want to take the overhead of a memory fence on every assignment to it. Is there any easy way to do that with Visual C++ source? A: Is there any way in Visual C++ to get the "C" volatile behaviour only, without the memory fence? On x86 there are no memory fences created at the assembly level on reads and writes to a volatile memory location since on that platform every load has acquire semantics, and every store has release semantics. Therefore for MSVC on x86, the volatile directive simply directs the compiler to prevent the reordering of loads and stores depending on if you are writing or reading from the memory location that was marked volatile. You would only incur the "penalty" of a memory fence on the IA64 architecture, since there the memory ordering model of the platform does not ensure acquire and release semantics for loads and stores. Keep in mind this behavior is MSVC-specific, and is not a standardized semantic of volatile. Update: According to @ildjarn you would also see a memory fence on ARM with Windows 8 since that platform also has a weakly ordered memory-consistency model like IA64.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: php + windows servers: remote transfer I need to have a file-uploader on a website that puts the uploaded file to a specific directory on a db server (unfortunately both are Windows). The web server has apache2.2 and php (plus cURL). The Db server is running MySQL. How do I do that/which secure protocol should I use (that is not FTP-based)?(soon, but not soon enough, everything will be moved to Linux, so it doesn't have to be pretty—just secure) Thanks! Edit I can have users added to either system if necessary for authentication
{ "language": "en", "url": "https://stackoverflow.com/questions/7504647", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make CONNECT BY parameter optional I have a procedure that uses Connect By SELECT <lots of fields> FROM Group g <joins> WHERE <where> CONNECT BY PRIOR g.ID = g.ParentID START WITH g.ID = 1337 ORDER SIBLINGS BY g.Name ; The number 1337 is a parameter on this procedure, if this value is 0 I would like to ignore the connect by code and execute everything else. How can I handle this? A: The most obvious answer is to test for the exception value in the connect by clause: SELECT <lots of fields> FROM Group g <joins> WHERE <where> CONNECT BY PRIOR g.ID = g.ParentID and :param <> 0 START WITH g.ID = :param or :param = 0 ORDER SIBLINGS BY g.Name;
{ "language": "en", "url": "https://stackoverflow.com/questions/7504648", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: java.lang.IllegalStateException: Cannot deserialize BeanFactory with id org.springframework.web.context.WebApplicationContext i am using spring 3 with JSF 2, Tomcat 6 and i replaced JSF managed beans with spring beans, by adding on top of bean: @Component("mybean") @Scope("session") and in my bean i am autowiring a spring service (which was declared with the annotation @service) both spring bean (jsf managed bean/controller) and my spring service implements serializable. well, everything works fine , but sometimes, i am getting this exception : java.lang.IllegalStateException: Cannot deserialize BeanFactory with id org.springframework.web.context.WebApplicationContext:/myapp: no factory registered for this id at org.springframework.beans.factory.support.DefaultListableBeanFactory$SerializedBeanFactoryReference.readResolve(DefaultListableBeanFactory.java:972) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at java.io.ObjectStreamClass.invokeReadResolve(ObjectStreamClass.java:1061) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1762) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329) at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1947) at java.io.ObjectInputStream.defaultReadObject(ObjectInputStream.java:480) at org.springframework.aop.support.AbstractBeanFactoryPointcutAdvisor.readObject(AbstractBeanFactoryPointcutAdvisor.java:98) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:974) at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1849) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329) at java.io.ObjectInputStream.readArray(ObjectInputStream.java:1667) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1323) at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1947) at java.io.ObjectInputStream.defaultReadObject(ObjectInputStream.java:480) at org.springframework.aop.framework.AdvisedSupport.readObject(AdvisedSupport.java:550) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:974) at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1849) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329) at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1947) at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1871) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329) at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1947) at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1871) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329) at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1947) at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1871) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329) at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1947) at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1871) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329) at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1947) at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1871) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329) at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1947) at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1871) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351) at org.apache.catalina.session.StandardSession.readObject(StandardSession.java:1496) at org.apache.catalina.session.StandardSession.readObjectData(StandardSession.java:998) at org.apache.catalina.session.StandardManager.doLoad(StandardManager.java:394) at org.apache.catalina.session.StandardManager.load(StandardManager.java:321) at org.apache.catalina.session.StandardManager.start(StandardManager.java:648) at org.apache.catalina.core.ContainerBase.setManager(ContainerBase.java:446) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4631) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057) at org.apache.catalina.core.StandardHost.start(StandardHost.java:840) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057) at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463) at org.apache.catalina.core.StandardService.start(StandardService.java:525) at org.apache.catalina.core.StandardServer.start(StandardServer.java:754) at org.apache.catalina.startup.Catalina.start(Catalina.java:595) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414) please advise. A: Well, finally i was able to make it work fine as follows: 1- The Service: @Service @Scope("singleton") public class PersonService{ } 2- The Spring Managed Bean: @Component("person") @Scope("session") public class PersonBean implements Serializable{ @Inject private PersonService personService; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7504652", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What do I have to do so that a property will show at the datasource? This is a windows forms question. forgive me if I explain what I do with too much detail but I asked with less detail before and it seems nobody read, because answers were completely off mark and I wasted bouty. I have a Linq object called XX. It was created when I dropped my table on the .dbml file in visual studio. Then, to make my interfaces easier to program I go to Data->Show Data Sources on visual Studio and create a object data source. All properties of the object appear at the data source. But the linq class is partial, so i do: partial class XX { private int _myValue; public int myValue { get { return _myValue; } set { _myValue = value; } } } are you following so far ? Then i go and recreate the object data source. The property myValue does not show on the data source. I tried decoratin it like this: [Bindable(true)] public int myValue to no avail. This usualy does the trick for "non-linq" Plain classes. So, the question is: What do I have to do so my property will show at the data source ?
{ "language": "en", "url": "https://stackoverflow.com/questions/7504654", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: FileNotFoundException in a testing a Maven module I'm working on a recently mavenized legacy project with following multi-modular structure: Parent: * *Web *Service *Dao ("Service" module is dependent on "Dao" module) Problem: some tests of Service classes call DAO code that creates beans using Spring's ClassPathXmlApplicationContext (this part is not really DAOs but caching related). Since, ClassPathXmlApplicationContext uses spring config xml of the DAO module - the Service tests fail throwing FileNotFoundException. I think this is because tests run in Service module and the spring config xml being referred lies in Dao module. Please advise on how can I resolve the above issue in tests referring to code/resources of other modules? A: Put a copy of the Spring configuration under src/test/resources in the Service module. Quite often you want a different configuration for testing anyway, but also it means your tests are less dependent on configuration changes in another module.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504658", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: signed_request as $_GET not $_POST The application I'm working on has rewrite rules in place to ensure that the user is always on https. In my fb application settings, I can define both the secure and nonsecure canvas page to use https (so no redirection will occur) but I cannot do the same on a tab page of the application. FB uses whatever protocol the user is running on as far as I can tell. Because of this, when a user hits the application via http, mod_rewrite redirects the user to the https version. Redirects don't pass along form data. There was a thread I found that discussed using a proxy redirect but that doesn't seem to be working. Is there some configuration setting I could use to turn my signed_request $_POST into a $_GET? Alternatively is there some api call I could make to get the signed_request? The facebook->getSignedRequest() simply looks in the $_REQUEST which due to the redirect contains no post data. A: I'd do the redirect in PHP (using $_SERVER['HTTPS']) rather than via .htaccess, and do it after first saving the signed request data to the user's session. A: I have the same problem here. When I visit the tab using HTTPS I get the signed_request just fine because there's not redirect happening. I run another Facebook app on the same server and it uses an htaccess file to make sure the files are served over HTTPS. So, What I ended up doing was making sure that the sub folder I'm working in is excluded from the rewrite. Like so: RewriteCond %{THE_REQUEST} !/my-app-folder Then, in my PHP I do a check to see if the referer is HTTP. If it is not, I change the header to an HTTPS version of my app. Like so: $referer = $_SERVER['HTTP_REFERER']; if (substr($referer,0,5) != 'https') { header("Location: https://www.facebook.com/myapp?sk=app_xxxxxxxxxxxxxx"); } This is probably not fool proof, but once I click that like button, I definitely get the results I need. I tested this in the dreaded IE as well and it appears to be working there too. A: Some browsers do redirect your request to https automatically if you have been on this particular site on https so if you are in http mode on facebook there is situation: facebook requests http version of your app, browser redirect this request of facebook to https and POST data and thus signer_request are gone in this process... i see this problem in chrome 23, if you delete browsing data (particulary "Deauthorize content licenses") app should run back on http
{ "language": "en", "url": "https://stackoverflow.com/questions/7504662", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to specify map properties in Struts 2 JSON Plugin I'm using Struts 2 along with the json plugin, the properties mappings in the struts.xml file are typically frustrating but I am able to figure them out. I have come across a case where I cannot set the includeProperties to give me the result I expect. Frequently I use a configuration expression ^itemList\[\d+\]\.id, ^itemList\[\d+\]\.name .... This works well. In this case I would like to return data from a Map not a list (or a map that's a child of a list member) If a * is used the whole map is printed out correctly, but I do not want all the data from the map elements. ^itemList\[\d+\]\map\.* The whole map is returnd I have tried several different formats and none of them have produced results. ^itemList\[\d+\]\map\[\d+\]\.id ^itemList\[\d+\]\map\[\d+\]\.name Nothing is returned in the map property Anyone had any luck with a syntax to restrict the contents of a map? Thanks -Scott A: You cannot use 'd' it map as integer. Try this ^itemList\..*$ A: 1) Your regular expression is suspicious. Note that in the expression "^itemList[\d+]\map[\d+].id", +d refers to one more more digits, so the map would have to have digit(s) as it's key. If this is not what you want, then '.+' is probably more appropriate (one or more of any character). 2) Convert the Map to a LinkedHashMap and then treat it as a list. (Have not tested this, it might not work)
{ "language": "en", "url": "https://stackoverflow.com/questions/7504663", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: trying to save time with PHP if/elseif statements I have a rather big if statement: if (!$result_spam) { $confrim_spam = "FAILED"; } else if ($result_spam) { $confrim_spam = "PASSED"; } if (!$result_email_manage) { $confrim_email_manage = "FAILED"; } else if ($result_email_manage) { $confrim_email_manage = "PASSED"; } if (!$result_analyt) { $confrim_analytics = "FAILED"; } else if ($result_analyt) { $confrim_analytics = "PASSED"; } Now I want to do another if statement to check if all have PASSED or if all have FAILED or is some have PASSED and some have FAILED and then echo (do something with) the failed ones. I know how to check if all have passed or failed: if ($confirm_spam == "PASSED" AND $confirm_analytics == "PASSED" but to check if some have passed and some haven't and then find the ones that failed will take too long, right? I was just wondering, would there be an easier/quicker way to do this? A: Since they are all bools anyway: if($result_spam && $result_email_manage && $result_analyt){ //do all passed } elseif($result_spam || $result_email_manage || $result_analyt){ //at least one passed if(!$result_spam){ echo '$result_spam failed';} if(!$result_email_manage){ echo '$result_email_manage failed';} if(!$result_analyt){ echo '$result_analyt failed';} } else { //do all failed } A: You can change validation logic to something like $passed = array(); $failed = array(); if (!$result_spam) { array_push($failed, "confirm_spam"); } else { array_push($passed, "confirm_spam"); } ... Then you have an easy and clear way to check whether all passed/failed and which tests are failed. A: What if you try this way: $passed = $failed = ""; $all = array("confrim_spam" => $result_spam, "confrim_email_manage" => $result_email_manage, "confrim_analytics" => $result_analyt); foreach($all as $a => $b) { if (!$b) $failed.= $a . ", "; else $passed.= $a . ", "; } Then if var $passed is empty, none passed else if $failed is not empty, at last one have not passed.. so do you got what passed and what failed and do something with them. And you can store results both in a string or an array whatever you want...
{ "language": "en", "url": "https://stackoverflow.com/questions/7504668", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to write a DQL select statement to search some, but not all the entities in a single table inheritance table So I have 3 entities within one table. I need to be able to search 2 out of the 3 entities in one select statement, but I'm not sure how to do this. A: The answer for multiple instances actually doesn't work. You would have to do something like this to check for multiple instances. $classes = ['Entity\Manager', 'Entity\Customer']; $qb = $this->createQueryBuilder('u'); ->where('u.id > 10') //an arbitrary condition, to show it can be combined with multiple instances tests ->andWhere("u INSTANCE OF ('" . implode("','", $classes) . "')"); A: As commented by flu, if you want to retrieve some entities from different instances with a QueryBuilder instead of a DQL query, you can use an array as parameter: $qb = $this->createQueryBuilder('u'); ->where('u.id > 10') //an arbitrary condition, to show it can be combined with multiple instances tests ->andWhere('u INSTANCE OF :classes') ->setParameter('classes', ['Entity\Manager', 'Entity\Customer']) ; A: Use the INSTANCE OF operator in your dql query like this (where User is your base class): $em->createQuery(' SELECT u FROM Entity\User u WHERE (u INSTANCE OF Entity\Manager OR u INSTANCE OF Entity\Customer) '); Doctrine translates this in the sql query in a WHERE user.type = '...' condition. See here for more details on the dql query syntax.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504680", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Expose Microsoft Access database over SQL Server using linked server We have one .exe application that uses one .mdb Microsoft Access database. I need to access data inside access file over Microsoft SQL Server. We have SQL Server 2008 R2 Enterprise that has linked server pointed to this Access file and I can run select / update query using SQL statement. SELECT * FROM [LinkedServerAccessDB]...[SomeTable] How can I configure that this linked server, my Access database, is directly published as "Database" when some application tries to connect to my SQL Server using SQL Server instance name, and username and password. Which "database name" should I use to use directly linked server ? Thank you A: It sounds like you want your MS Access Linked Server object available as a database (i.e. available in the 'Databases' folder in SSMS). This isn't possible, directly. Suggest you create a new SQL Server database that mimics the name of that Access database. Map a user to that login you've got above. Allow the user to run queries against the linked server. A: You can use CREATE SYNONYM like so. USE ASQLServerDB GO CREATE SYNONYM Sometable FOR LinkedServerAccessDB...SomeTable Once this is done you can write SELECT [...] from SomeTable as though it was a member of the database ASQLServerDB I was only able to get it to work at the object level so you'll need to do this for each object you want to expose. You could create an empty database that just contained these Synonyms if you wanted to get that "published as a database" feel. --This doesn't work CREATE SYNONYM Sometable FOR LinkedServerAccessDB...
{ "language": "en", "url": "https://stackoverflow.com/questions/7504685", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to get ALL combinations of a list of words using ANY number of words I have searched but I can't find anything that matches my query. I have seen lots of solutions where people want all combinations of numbers/words that use ALL the options, but none like this... Here's an example: apple pear This should generate: apple pear apple pear pear apple Or even... apple pear banana apple pear banana apple pear apple banana pear banana ... ... banana pear apple The key is, ALL possible combinations that use any of the words zero or one times in ANY order. :) A: FINAL ANSWER AT THE BOTTOM Pseudocode (has not been tested) $str = "apple pear banana"; $str_splode = explode(' ',$str); echo showCombo($str_splode[0], $str_splode); function showCombo($str, $arr){ $ret = ''; foreach($arr as $val){ if($val != $str) $ret .= $str.showCombo($val, $arr); } return $ret; } Running code: http://codepad.org/IUPJbhI7 <?php $str = "apple pear banana orange"; $str_splode = explode(' ',$str); print_r(showCombo(array(), $str_splode)); function showCombo($str_arr, $arr){ $ret = array(); foreach($arr as $val){ if(!in_array($val, $str_arr)){ $temp = $str_arr; $temp[] = $val; print_r($temp); $comb = showCombo($temp, $arr); if(count($comb) > 0) $ret[] = $comb; } } return $ret; } ?> This returns all possible combinations Or this one looks better: http://codepad.org/KCLeRUYs <?php $str = "apple pear banana orange"; $str_splode = explode(' ',$str); print_r(showCombo(array(), $str_splode)); function showCombo($str_arr, $arr){ $ret = array(); foreach($arr as $val){ if(!in_array($val, $str_arr)){ $temp = $str_arr; $temp[] = $val; $ret[$val] = $temp; $ret[$val][] = showCombo($temp, $arr); } } return $ret; } ?> Or if you want to look at flat keys: http://codepad.org/95aNQzXB Final Answer: And this one lists them all: http://codepad.org/vndOI9Yj <?php $str = "apple pear banana orange"; $str_splode = explode(' ',$str); $combos = showCombo(array(), $str_splode); foreach($combos as $key=>$array){ echo $key.PHP_EOL; displayArrayByKey($key, $array); } function displayArrayByKey($str, $arr){ foreach($arr as $key=>$array){ $string = $str. " " . $key; echo $string . PHP_EOL; if(count($array)> 0){ displayArrayByKey($string, $array); } } } function showCombo($str_arr, $arr){ $ret = array(); foreach($arr as $val){ if(!in_array($val, $str_arr)){ $temp = $str_arr; $temp[] = $val; $ret[$val] = showCombo($temp, $arr); } } return $ret; } ?> A: You can download this class: http://pear.php.net/package/Math_Combinatorics and use it like: $combinatorics = new Math_Combinatorics; $words_arr = array( 'one' => 'a', 'two' => 'b', 'three' => 'c', 'four' => 'd', ); for ($i=count($words_arr)-1;$i>=1;$i--) { echo '<br><br>' . $i . ':<br>'; $combinations_arr = $combinatorics->combinations($words_arr, $i); foreach ($combinations_arr as $combinations_arr_item) { echo implode(', ', $combinations_arr_item) . '<br>'; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7504687", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Repainting in Swing JComponent after an interval I have been assigned a project where I have to make an analog clock using the GregorianCalendar object in java. First, we were told to get the clock working, so that it shows the proper time on each run. Then we were told to make the clock redraw for every second that it is running. I made a timer object and thought I could add an ActionListener and have it repaint every time actionPerformed was invoked, but repaint obviously can't be used in this way. Here's my code: import javax.swing.*; import java.awt.event.*; import java.awt.geom.*; import java.awt.*; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Date; import javax.swing.Timer; import java.lang.Math; public class SwingClock { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { MyFrame frame = new MyFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ActionListener listener = new TimePrinter(); Timer t = new Timer(1000, listener); GregorianCalendar calendar = new GregorianCalendar(); t.start(); frame.setVisible(true); } }); } } class TimePrinter implements ActionListener { public void actionPerformed(ActionEvent event) { //I'd like to repaint here every second, but I can't } } class MyFrame extends JFrame { public MyFrame() { setTitle("Swing Clock"); setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); MyComponent component = new MyComponent(); add(component); } public static final int DEFAULT_WIDTH = 500; public static final int DEFAULT_HEIGHT = 500; } class MyComponent extends JComponent { public void paint(Graphics g) { Graphics2D g2 = (Graphics2D)g; int leftX = 50, topY = 50, width = 300, height = 300; Rectangle2D rect = new Rectangle2D.Double(leftX, topY, width, height); Ellipse2D clockFace = new Ellipse2D.Double(); clockFace.setFrame(rect); g2.draw(clockFace); double centerX = clockFace.getCenterX(); double centerY = clockFace.getCenterY(); GregorianCalendar calendar = new GregorianCalendar(); int hour = calendar.get(Calendar.HOUR_OF_DAY); int minute = calendar.get(Calendar.MINUTE); int second = calendar.get(Calendar.SECOND); double minusMinute = (90 - (minute*6))*(Math.PI/180); double minuteCosine = Math.cos(minusMinute); double minuteSine = Math.sin(minusMinute); double minusSecond = (90 - (second*6))*(Math.PI/180); double secondCosine = Math.cos(minusSecond); double secondSine = Math.sin(minusSecond); double hourTheta = (90-(hour+(minute/60)*30))*(Math.PI/180); g2.draw(new Line2D.Double(centerX,centerY,centerX+50*(Math.cos(hourTheta)), centerY - 50*(Math.sin(hourTheta)))); g2.draw(new Line2D.Double(centerX,centerY,centerX+150*(minuteCosine),centerY-150*(minuteSine))); g2.draw(new Line2D.Double(centerX, centerY, centerX+100*secondCosine, centerY-100*(secondSine))); } } Any ideas on how to get around this? Maybe I'm going about it wrong? A: "Swing programs should override paintComponent() instead of overriding paint()," although as you will see, this is not necessary at all. Second of all, you're right in using javax.swing.Timer. Third of all, why don't you make it easy on yourself and use a JLabel instance to display the time instead? A: * *MyComponent should be defined as a class variable in your MyFrame class *The Timer should be created and started in your MyFrame class. *The ActionListener for the Timer should invoke repaint on your MyComponent variable. *Your MyComponent class should extend JPanel, then you can just invoke super.paintComponent() as the first statement to clear the panel before drawing the clock at its new time. A: You just override constructor of Listener: class TimePrinter implements ActionListener { private MyFrame frame; TimePrinter(MyFrame frame){ this.frame=frame; } public void actionPerformed(ActionEvent event) { frame.repaint(); } } MyFrame frame = new MyFrame(); ActionListener listener = new TimePrinter(frame);
{ "language": "en", "url": "https://stackoverflow.com/questions/7504690", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: overloading resolution, cpp I understand that if there are several function with the same name and same number of parameters the compiler is trying to find the best match (am I right so far?) What I don't understand is the difference between type promotion and type conversion. Say I have this function decleration: void foo (double x) and then inside main: int x = 5; foo(x); Is that considered conversion or promotion? A: Type promotion is special case of type conversion. http://en.wikipedia.org/wiki/Type_conversion#Type_promotion A: Your example wont work you would need to have 2 methods for overloading 1.) void foo(double x){method code} and 2.) void foo(int x){method code} Then when you run the code int x = 5; foo(5) The compiler or run time environment knows which method to call based on the input type you passed in. If I want to convert an int into a double that is different. I am not sure what language you are using but in Java you would do the conversion using type casting this is type casting and will convert a double to an int. You will loose the decimal part if there is one. double d = 5; int i = (int)d; I think this is what you are asking. If not please clarify a little
{ "language": "en", "url": "https://stackoverflow.com/questions/7504695", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using Between on only time portion of dates I have the following query: SELECT COUNT(*) FROM leads WHERE create_date > '06:00' AND create_date < '18:00'; SELECT COUNT(*) FROM leads WHERE create_date > '06:00' AND create_date < '18:00'; However, the create_date column looks like '2011-08-26 10:18:01' and i want to find everything between just those time periods, regardless of the day. How can I just query the time from the create_date values? How would also find all values not within those time periods? NOT BETWEEN .... A: To get the time from the date, you can use the TIME() function. SELECT COUNT(*) FROM leads WHERE TIME(create_date) > '06:00' AND create_date < '18:00'; SELECT COUNT(*) FROM leads WHERE TIME(create_date) > '06:00' AND create_date < '18:00'; To find times outside this range, just invert everything in your where clauses. SELECT COUNT(*) FROM leads WHERE TIME(create_date) < '06:00' AND create_date > '18:00'; SELECT COUNT(*) FROM leads WHERE TIME(create_date) < '06:00' AND create_date > '18:00'; A: Use the TIME() function to return only the time portion of a DATETIME column. SELECT COUNT(*) FROM leads WHERE TIME(create_date) > '06:00' AND TIME(create_date) < '18:00'; To find the values outside these time periods, use SELECT COUNT(*) FROM leads WHERE TIME(create_date) <= '06:00' AND TIME(create_date) >= '18:00'; A: Assuming that create_date is of type DATETIME, to extract the time part only use TIME(create_date). And yes, NOT BETWEEN will get the inverse set. A: You can just cast to a TIME: SELECT COUNT(*) FROM leads WHERE TIME(create_date) > '06:00' AND TIME(create_date) < '18:00';
{ "language": "en", "url": "https://stackoverflow.com/questions/7504704", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java batch processing I will read 2000 files and do some works on them with java. So I think I should use batch processing. But How could I do? My system is Windows 7. A: You can use Apache Camel / Servicemix ESB in combination with ActiveMQ. Your first step would be to write the fileNames one by one in ActiveMQ Messages. This could be done in one so called route (a separate Thread automatically by the framework). Here you have several options which component to use. There is a file component which reads files and moves them to done afterwards or you can use a simple Java Bean. In a second route you read the Active MQ messages (single consumer if it is important to process the files in a sequence or multiple consumers if you want more performance) process the File Content in a processor or Java Bean like you want. You can stop the Camel context any time you want (during the processing) and restart it afterwards getting the process started at the next file not yet processed by loading / consuming it from the Active MQ message queue. A: Java does not provide built in support for batch processing. You need to use something like Spring Batch. A: Check this out: http://jcp.org/en/jsr/detail?id=352 This is a new "Batch" on JSR - javax.batch A: You can't read files as a batch. You have the read one at a time. You can use more than one thread but I would write it single threaded first. It doesn't matter what OS you are using. A: Assuming you have the ability to work on one file, you have two options: use a file list, or recur through a directory. It gets trickier if you need to roll back changes as a result of something that happens towards the end, though. You'd have to create a list of changes to make and then commit them all at the end of the batch operation. // first option batchProcess(Collection<File> filesToProcess) { for(File file : filesToProcess) processSingle(file); } // second option batchProcess(File file) { if(file.isDirectory()) { for(File child : file.listFiles()) { batchProcess(file); } } else { processSingle(file); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7504705", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Anchor tag not working inside absolutely positioned div I have created an unordered list inside a div which is absolutely positioned. When I add an href inside of the li items, it's not working. For example: <li><a href="index.html">Home</a></li> is still not clickable. Here is the CSS (the nav is the wrapping div): #nav { background:#666666; position:absolute; top: 270px; left:150px; height:40px; } #nav ul li { position:relative; top:-8px; left: -15px; display:inline; padding: 0 33px; font-size:14px; border-right: 2px solid #333333; margin:auto; color: #efefef; } Here's the full code. I also figured out that some other element is overlapping, but don't know what to do. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Good Brothers Film Entertainment</title> <link rel="stylesheet" href="css/default.css" type="text/css"/> </head> <body> <div id="container"> <div id="header"> <img src="images/logo2.png" id="logo2"/> <img src="images/logo.png"/> </div> <div id="nav"> <ul> <li><span>H</span>OME</li> <li><span>S</span>ERVICES</li> <li><span>R</span>EELS</li> <li><span>G</span>ALLERY</li> <li><span>A</span>BOUT US</li> <li><span>C</span>ONTACTS</li> <li><span>A</span>FFILIATES</li> </ul> </div> </div> <img src="images/inner-background.png" id="inner-background" /> <p id="welcome">~<span>W</span>ELCOME~</p> <img src="images/good-brother.png" id="good-brother"/> <img src="images/working-together.png" class="work-together" /> <img src="images/and.png" class="work-together" /> <img src="images/exceeding-limits.png" class="work-together" /> <img src="images/men.png" class="men" /> <img src="images/men-shadow.png" class="men" /> <img src="images/footer.png" id="footer" /> <div id="video"> <!-- <iframe width="560" height="315" src="http://www.youtube.com/embed/V0LQnQSrC-g" frameborder="0" allowfullscreen></iframe> --> </div> </body> </html> The CSS body,html{margin:0;border:0;padding:0;} #container { width:1360px; height:1024px; background:url(../images/background.png); } #logo2 { position:absolute; } #nav { background:#666666; position:absolute; top: 270px; left:150px; height:40px; } #nav ul li { position:relative; top:-8px; left: -15px; display:inline; padding: 0 33px; font-size:14px; border-right: 2px solid #333333; margin:auto; color: #efefef; } #nav li span { font-size: 21px; } #nav li:last-child { border:none; } #inner-background { position:absolute; top: 0px; } #welcome { color:#ffffff; top:300px; left:300px; font-weight:bold; font-size:24px; position:absolute; } #welcome span { font-size: 28px; } #good-brother { top:1px; position:absolute; } .work-together { top: -5px; position:absolute; } #video { top: 400px; left:600px; height:315px; width:560px; background: #eeeeee; position: absolute; } .men,#footer { top:1px; position: absolute; } A: Depending on your layout, you can use z-index set to a high enough value allowing the anchor tags to overcome the overlapping element. A: Still work with the complete code, but with no images. I suspect that your problem is the #footer image (I can confirm it is if the image is over 300 pixel high!) Here's why : .men,#footer { top:1px; position: absolute; } Since this image is defined after, it's put on top. It's either that image or another one big enough to cover your header. This css declaration could help find if an image is the culprit : img {border:3px solid red !important;} If you have firebug or other similar developpement tool, right click on your link and do inspect element : if you have an element over it, it should be selected. Note : if you dont have firebug or something similar... Get one asap.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504706", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Linux udev rule does not appear to work I am writing an application that MUST run on Fedora Core 4. The application needs to access a USB device WITHOUT root privileges. Using libusb-1.0.8 I have successfully written the application except for one problem. If I do not have root privileges, libusb_open fails with -3 "Permission Denied". I've read that I can alter the permissions of the device with a udev rule. And so I added 10-local.rules to /etc/udev/rules.d with the following line: BUS=="usb", SYSFS{idVendor}=="040a", SYSFS{idProduct}=="4e00", MODE="0666" I copied the above information from the output of udevinfo. Even with the above rule, the device permissions always end up "0644" and I cannot open the USB device from a user application. Even after rebooting. Does anyone have any suggestions as to what I may be doing wrong? Does Fedora Core 4 support what I am trying to do? Thanks A: Udev sets usb permissions after your script runs. Rename your rule so that the filename starts with a number greater than 50 (USB Permissions are set in the /lib/udev/rules.d/50-udev-default.rules). Since your script name is 10-..., it is run first, then the permissions are reset. Changing the filename to, for example, 99-local.rules. Then it will be one of the last scripts run, and none of the settings will be overwritten. Source: http://virtuallyhyper.com/2013/02/fixing-android-phone-device-permissions-on-fedora-17/ A: Try something like: ACTION=="add", SUBSYSTEM=="usb", ATTRS{idVendor}=="04e8", ATTRS{idProduct}=="5090", MODE="0666" Conditions in the udev rules are tricky at best. You can check what parameter are available with the command: udevadm info --attribute-walk --name=<device> The output also includes the following notice: A rule to match can be composed by the attributes of the device and the attributes from one single parent device. Also note the ending S in some attribute names. It appears in the parent devices, but not in the device itself. A: Modifiying permissions for USB devices seems to be handled at least 3 different ways depending on the version of Linux (HAL, udev, hotplug, etc.). After several unsuccessful attempts I finally came across a site with accurate information. For Linux 2.6.11 at least, the answer is hotplug. The solution is to create a custom usermap file in /etc/hotplug/usb. Use the built-in usermap (/etc/hotplug/usb.usermap) as an example. The usermap file specifies a script to execute when a matching device is connected. The script should also be located in /etc/hotplug/usb. For example, I created /etc/hotplug/usb/myusbdvc.usermap with the VID and PID of my device and a script to execute named chmodmyusbdvc. I also created /etc/hotplug/usb/chmodmyusbdvc with the follow contents: #!/bin/bash if [ "${ACTION}" = "add" ] && [ -f "${DEVICE}" ] then echo "changing ${DEVICE}" >> /tmp/debug-hotplug chmod 666 "${DEVICE}" fi
{ "language": "en", "url": "https://stackoverflow.com/questions/7504707", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Background Position not Animating - jQuery Hey Folks I have a little issue today. I am trying to create an animated Menu but its just not working. Any got any clue? Below is the issue. jQuery Code $(document).ready(function(){ $("ul li").hover(function(){ $(this).animate({backgroundPosition: "50% 100%"}); }, function(){ $(this).animate({backgroundPosition: "50% -100px"}); }); }); CSS Code background-color:transparent; background-image:url(../images/menu_sel.png); background-repeat:no-repeat; background-position:50% -100px; HTML Code <ul> <li><a href="#">Home</a></li> <li><a href="#">Another Page</a></li> </ul> I even tried mouseover in jQuery but no go :( $("ul li") .mouseover(function(){ $(this).stop().animate({backgroundPosition: "50% 100%"}); }) .mouseout(function(){ $(this).stop().animate({backgroundPosition: "50% -100px"}); }) I also tried simple CSS replacement and it works... but not the animation :( $("ul li") .mouseover(function(){ $(this).css({backgroundPosition: "50% 100%"}); }) .mouseout(function(){ $(this).css({backgroundPosition: "50% -100px"}); }) I cannot get it to work... any clues?? A: jQuery cannot animate complex css values.. it's the same reason you can't do something like: $('#thing').animate({margin: "10px 0 0 10px"}); You'll have to animate the individual properties, such as: $('#thing').animate({backgroundPositionX: "50%", backgroundPositionY: "-100px"}); A: It seems that jQuery does not support animation two values at once, try: $(this).animate({backgroundPositionY:-100}); A: Figured it out! As suggested by all here, jQuery does not handle complex positioning. So below is what finally worked!! .mouseover(function(){ $(this).stop().animate({backgroundPosition: "50% 0"}, {duration:200}); }) .mouseout(function(){ $(this).stop().animate({backgroundPosition: "50% -54px"}, {duration:200}); }) Cheers!
{ "language": "en", "url": "https://stackoverflow.com/questions/7504714", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WH_JOURNALPLAYBACK hook in C# I am trying to create a callback for "WH_JOURNALPLAYBACK" hook in C#. This is the code private delegate IntPtr JournalPlaybackProc(int nCode, IntPtr wParam, IntPtr lParam); private static IntPtr JournalPlaybackCallback(int nCode, IntPtr wParam, IntPtr lParam) { if (HC_GETNEXT == nCode && curr < EventMsgs.Count) { EVENTMSG hookStruct = (EVENTMSG)Marshal.PtrToStructure(lParam, typeof(EVENTMSG)); EVENTMSG currentMsg = EventMsgs[curr]; hookStruct.message = currentMsg.message; hookStruct.paramL = currentMsg.paramL; hookStruct.paramH = currentMsg.paramH; hookStruct.hwnd = currentMsg.hwnd; hookStruct.time = currentMsg.time; } if (HC_SKIP == nCode) { curr++; } if (curr == EventMsgs.Count) { UnhookWindowsHookEx(_journalPlaybackProcHookID); _journalPlaybackProcHookID = IntPtr.Zero; } return CallNextHookEx(_journalPlaybackProcHookID, nCode, wParam, lParam); } I get the callback correctly, i suppose i need to modify the value of lParam with my data to playback the events. How do i do this? A: I assume you need to Marshal.StructureToPtr(hookStruct,lParam,true); To write it back at some point. When I run it just hangs though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504716", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Example from ?aggregate documentation generates error Why is this not working for me: I pasted in the following example from R help: aggregate(. ~ Species, data = iris, mean) I am getting following error every time Error in m[[2L]][[2L]] <- parse(text = lhs)[[1L]] : object of type 'symbol' is not subsettable However the following works: aggregate(len ~ ., data = ToothGrowth, mean) Surprised ... Edits: session information is provided > sessionInfo() R version 2.12.2 (2011-02-25) Platform: x86_64-pc-mingw32/x64 (64-bit) locale: [1] LC_COLLATE=English_United States.1252 LC_CTYPE=English_United States.1252 LC_MONETARY=English_United States.1252 [4] LC_NUMERIC=C LC_TIME=English_United States.1252 attached base packages: [1] splines stats graphics grDevices utils datasets methods base other attached packages: [1] doBy_4.4.0 MASS_7.3-11 snow_0.3-6 lme4_0.999375-39 Matrix_0.999375-46 lattice_0.19-17 [7] multcomp_1.2-6 mvtnorm_0.9-96 R2HTML_2.2 survival_2.36-5 reshape_0.8.4 plyr_1.4 [13] rcom_2.2-3.1 rscproxy_1.3-1 Biostrings_2.18.4 IRanges_1.8.9 loaded via a namespace (and not attached): [1] Biobase_2.10.0 grid_2.12.2 nlme_3.1-98 stats4_2.12.2 tools_2.12.2 A: This question is partially solved. I used a fresh R session, pasted code and got what I want. Potentially the package or something I define in the session are causing problem ( I do not know), as suggested here see prov.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504718", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Regular expression to validate length string without including html tags I am using umbraco where the validation on fields is done by regular expressions. In one field I want to allow users to style their text using the rich text editor (tinymce) but I still want to limit the number of characters they can enter. I'm currently using this regular expression but it checks the total number of characters so includes the html. ^[\s\S]{0,250}$ Is there a regular expression that wouldn't count the characters in html tags. A: The short answer is no. At least, not with any sane regex, not without an advanced regex engine that allows recursion or balanced groups, and maybe not at all. A regex that can recognize and ignore HTML tags would have to parse the HTML to do it, and down that road lies madness. However, you could use some sort of preprocessing, such as jQuery on the client-side or something else on the server-side, to parse the HTML and strip out the tags before you apply length validation. Are you sure you want to do this, though? If you're storing the styled input in a database, then those HTML tags are going to count against your column size just like everything else will. If you're storing these in a varchar(250) column, you're going to have to either count the HTML tags as part of that 250, or else strip them out and lose all the style information. A: It's going to be hard (nigh impossible) to do this in one step, since the grammar you're trying to detect is not context-free. Two steps would be easy; just do a s/<.+?>// substitution first to remove all the tags then count again. On a related note, your regex above is a little bit silly. You can use the . character to represent any character; you don't have to do the "whitespace OR not-whitespace" trick you're using. ^.{0,250}$
{ "language": "en", "url": "https://stackoverflow.com/questions/7504720", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Black backgrounds on interactive windows launched from a service I am implementing a Windows service in C#. This service calls a separate application that launches interactive windows. I have been able to work through the problems imposed by Session 0 Isolation by using the following series of steps: * *LogonUser() to get a logon token for the user who will execute the separate application *SetTokenInformation() to transfer the user's logon token into session 1 *CreateProcessAsUser() to launch the application in the user's session. This works; When the service launches the application, I see the application's windows appear in my console session. However, the application's windows have black backgrounds and all of the controls are invisible. If I click in an area where I know there is a button, the window responds, so it is clearly able to receive user input. Here is (a simplified and stripped down version of) the code I'm using: IntPtr logonToken; LogonUser(username, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out logonToken); SetTokenInformation(logonToken, TOKEN_INFORMATION_CLASS.TokenSessionId, sessionIdValuePtr, sessionIdSize); STARTUPINFO startupinfo = new STARTUPINFO(); startupinfo.cb = Marshal.SizeOf(startupinfo); startupinfo.lpDesktop = @"winsta0\default"; PROCESS_INFORMATION processinfo; SECURITY_ATTRIBUTES processAttributes = new SECURITY_ATTRIBUTES(); SECURITY_ATTRIBUTES threadAttributes = new SECURITY_ATTRIBUTES(); ImpersonateLoggedOnUser(logonToken); CreateProcessAsUser( logonToken, null, cmdLine, ref processAttributes, ref threadAttributes, false, 0, IntPtr.Zero, workingDirectory, ref startupinfo, out processinfo) RevertToSelf(); I have tried adding code to load the user's profile before calling CreateProcessAsUser, but this did not help. What could be causing the black backgrounds on my windows, and how should I go about fixing this problem? Any help would be most appreciated. UPDATE: This appears to be very similar to the problem in this question: CreateProcessAsUser doesn't draw the GUI. He is using XP SP3, and I am having this problem in Windows 7 and Server 2008, meaning that I have the additional problem of dealing with Session 0 Isolation, but the symptoms in the two cases seem similar.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504721", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Finding existing ShiroRoles to add to a New ShiroUser using Grails? How can I retrieve an existing ShiroRole that I've already created and stored in the database? I've noticed that you can retrieve an existing ShiroUser by calling ShiroUser.findByUserName("somename") but I haven't found a method in ShiroRole that appears to do the same in finding the role by name. I'm using the Apache Shiro Grails Plugin Thanks! A: If you're using the Shiro Grails Plugin and the ShiroRole that it installs by default, it's really just a standard Grails domain class, so you should be able to do ShiroRole.findByName('roleName').
{ "language": "en", "url": "https://stackoverflow.com/questions/7504724", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP: Has this code performance issues? Can be improved? I'm trying to make some SEO improvement on my site. I'd like to add some text to my URLs. I'm trying to add information to the URLs. I get the "product name" (or title) from an item and append it to the URL. So, if a "Core 2 Duo 8600 CPU" has id 10, the old URL was: example.com/cpu/10 Now, i want to append the product name, so it will be: example.com/cpu/10/core-2-duo-8600-CPU/ The problem is that i don't want special chars in there, nor accented words (it's a spanish site), so i built this function: function makeFriendlyURL($string){ $search = explode(",","ç,æ,œ,á,é,í,ó,ú,à,è,ì,ò,ù,ä,ë,ï,ö,ü,ÿ,â,ê,î,ô,û,å,e,i,ø,u"); $replace = explode(",","c,ae,oe,a,e,i,o,u,a,e,i,o,u,a,e,i,o,u,y,a,e,i,o,u,a,e,i,o,u"); $string = str_replace($search, $replace, $string); $string = preg_replace("/[^A-Za-z0-9]/"," ",$string); $string = preg_replace('/\s+/', '-',trim($string)); return strtolower($string); } makeFriendlyURL('Técnico electricista') //tecnico-electricista (accented é is replaced with e) makeFriendlyURL('RAM 1066/1333') // ram-1066-1333 (striped the slash and lowercase "RAM") Now, do you see any issue? I think it could be improved, but don't know how. A: Can this code be improved? In these situations it's easier to define with what you want than what you don't want, as that is an every changing list. This is typical code that will create a slug from a title: // translate accented chars $search = explode(",","ç,æ,œ,á,é,í,ó,ú,à,è,ì,ò,ù,ä,ë,ï,ö,ü,ÿ,â,ê,î,ô,û,å,e,i,ø,u"); $replace = explode(",","c,ae,oe,a,e,i,o,u,a,e,i,o,u,a,e,i,o,u,y,a,e,i,o,u,a,e,i,o,u"); $string = str_replace($search, $replace, $string); // create slug by replacing non-alphanumeric chars with a dash $slug = trim(preg_replace('/[^a-z0-9]+/', '-', strtolower($string)), '-'); Note: as a URL, I've added strtolower(). Feel free to remove it if you truly want capitals in your URL.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504725", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: PrototypeJS - Cloning Input, Retains Checkboxes Even After removeAttribute in Firefox I am cloning a row, changing some things in the element, then outputting the element to the page. the problem is, when I remove the checked attributes, it works fine in IE, but FF retains the checked state from the original element that was cloned. For example: var newHTML = $$('.importRow')[0].clone(true); $(newHTML).select('input').each(function(s, index) { $(s).removeAttribute('checked'); //This is to remove any checked value if ($(s).hasClassName('someClass') && $(s).getValue() == 'someValue'){ //This is to assign a new default checked value $(s).setAttribute('checked','checked'); } } $(this).up().insert({ before: newHTML }); How would I get around this and make FF not retain the previously selected values? EDIT: Returning the element it shows it correctly, but Firefox remembers the value for some reason and I am not sure how to override this behaviour. A: Try using the checkbox DOM attributes: s.checked = false; s.defaultChecked = false;, or alternatively, instead of removing the checked attribute, set its value to false: s.writeAttribute('checked', 'false'); Incidentally, once an element has been extended with the prototype functions, you don't need to repeatedly call $() on it; this just wastes CPU time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504726", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: VB.NET How To Tell If New Class Instance Was Ended Early? I'm trying to detect if the Sub New() in my class has ended early due to missing fields. Below is a sample of my code: Class Account Public Sub New(ByVal Firstname As String, ByVal LastName As String, ByVal Username As String, ByVal Email As String, ByVal Password As String) ' Check For Blank Fields If Firstname = "" Or LastName = "" Or Username = "" Or Email = "" Or Password = "" Then MessageBox.Show("Please Enter All Information Requested") Exit Sub End If ' Set Public Variables Of Class Firstname = Firstname LastName = LastName Username = Username Email = Email Password = Password End Sub Public Shared Sub OtherUse() End Sub End Class ' Create New Instance Dim Process As New Account(txtFirstName.Text, txtLastName.Text, txtUsername.Text, txtEmail.Text, txtPassword.Text) ' HERE - How Can I Catch The Early Exit From The Instance Due To Potential Missing Fields? ' Use Instance For Other Use Process.OtherUse() How would I catch the Exit Sub from the class in the parent form to prevent the further processing of Process.OtherUse()? A: You're approaching this problem the wrong way. Validate the input first, and then once the input is valid, create a new Account using New. Another option would be to initialize data in New without checking if it's valid or not, then have an IsValid method in that class that you would call from another class to know whether or not the messagebox should be shown. One way or another, the Account class shouldn't be responsible for a UI concern like showing a MessageBox on the screen. And the constructor should only be responsible for constructing the object, not validating the input, because you can't "abort" a constructor. You have a reference to a new object even though you call Exit Sub. A: A fourth alternative, in addition to the three mentioned by Meta-Knight: Have the constructor throw an exception when the parameters aren’t valid. As an aside, your use of Or, while working, is a logical error: And and Or are bitwise arithmetic operations. You want a logical operation, OrElse (there’s also AndAlso). These may seem similar to Or and And and in this particular case, both happen to work. But they are actually quite different semantically, bitwise operations are just wrong here (it’s a pity that this code even compiles. The compiler shouldn’t allow this).
{ "language": "en", "url": "https://stackoverflow.com/questions/7504732", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Create Silverlight Control that can be used as the layout root How can I create a control in silverlight that can be used as the layout root, but still have a "Template" property so I can wrap the users content inside another control using a style? My current implementation is close, it takes the content that the user places in the control and wraps it but the user has to put a grid or panel in if there is multiple controls for the content. --Update -- This is the code I'm using that will not work as the rootlayout for multiple children unless the user puts a grid around their content. If I inherit from Grid or Panel I get an error about the DefaultStyleKey property not being available. public class BusyControl :ContentControl { public BusyControl() { this.DefaultStyleKey = typeof(BusyControl); } } <Style TargetType="local:BusyControl"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="local:BusyControl"> <telerik:RadBusyIndicator DisplayAfter="0:0:0.5" IsBusy="{Binding IsBusy}" BusyContent="{Binding BusyMessage}"> <ContentPresenter Content="{TemplateBinding Content}" Margin="{TemplateBinding Padding}"/> </telerik:RadBusyIndicator> </ControlTemplate> </Setter.Value> </Setter> </Style> This is how I want the user to be able to use my new control with out having to wrap their content in a panel or grid. <cdc:BusyControl x:Name="BusyControl"> <some:Control x:Name="Control1" /> <some:Control x:Name="Control2" /> </cdc:BusyControl> A: Seems to me that what you want is to derive your control from an ItemsControl not a ContentControl. In any ControlTemplate that you use you can place the controls using an ItemsPresenter instead of the ContentPresenter you would have used in a ContentControl. A: I think that if you want multiple controls, i.e. children, as content then you have to use some sort of panel, which is the base class for the .Children property. Not sure if this is applicable to your situation. I had trouble grasping exactly what's going on in your question. Maybe you can make a custom user control that inherits from ContentControl. As you may or may not know, custom user controls need a default style key. With a custom user control you need to define a template in the default style. Now the template can have a ContentControl somewhere inside of it and its content property should be template binding to the contentcontrol.content property. Or you can override the OnContentChanged function and do whatever you want in that override function (like put a single object in the control by itself... or for multiple objects create a new grid/panel and then set the objects as the grid/panels children for the user and then do what ever it is you are doing with the grid/panel. You would have to set/bind the content property on your new control. Make sense? I don't know about your error with the default style key, and i don't have any telerik controls, but couldn't you just inherit from your telerik busy indicator? Would something like this work for you, (or put you on the right track). protected override void OnContentChanged( object oldContent, object newContent ) { //I dont know how you are assigning content, //but i would say if it's IEnumerable and count is > 1 it should use your panel var newMultiContent = newContent as System.Collections.IEnumerable; if ( newMultiContent!=null && newMultiContent.Cast<object>().Count()>1) { var myNewContentContainer = new StackPanel();//or grid or whatever myNewContentContainer.Children.Clear(); //add children foreach (var item in newMultiContent.OfType<UIElement>()) myNewContentContainer.Children.Add(item); //instead of the old content that wasn't what you wanted, use the new content container base.OnContentChanged( oldContent, myNewContentContainer ); //or maybe try this and call the base method at the beginning... Content = myNewContentContaint } else base.OnContentChanged( oldContent, newContent ); } A: You can have your control inherit from Panel if you want it to be able to have multiple children. You will have to handle laying out the panel's child controls if you do this. See this MSDN article on creating custom panels. You can then specify your Template and stick the user content into the template.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504734", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PHP compare HTML characters array Solution I got a value in $arrNew[4], I want to run a foreach loop on $arrNew and check if a value is equal to $arrNew[4]. I want to compare $arrNew with the value in $arrNew[4]. The problem is, that value isn't there most of the times, so i want it as a string so i can use it on other parts. But if I echo $arrNew[4] out I get "vrij &nbsp &nbsp " It isn't the same as in $arrNew[4] because I can't do $forNew == "vrij &nbsp &nbsp " but I can do $forNew == $arrNew[4] How should I do this ? Any help is appreciated :) foreach ($arrNew as $forNew) { $forCount = $forCount + 1 ; if($forNew == $arrNew[4]) { echo "Vrij: ".$arrOld[$forCount] ; } } A: Have you take a look at http://www.php.net/manual/en/function.array-diff.php
{ "language": "en", "url": "https://stackoverflow.com/questions/7504735", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Classic asp file upload with jquery goodness? Is there a combination of Classic ASP file uploading and JQUery that you've used to make a clean and solid Classic ASP Upload/progress bar/ajax solution? A: File Upload widget with multiple file selection, drag&drop support, progress bars and preview images for jQuery. Supports cross-domain.. Classic ASP https://github.com/blueimp/jQuery-File-Upload/wiki/Classic-ASP A: My current favourite on the client side is Plupload which if you disable chunking works fine with classic ASP scripts, and the ASP side can be as simple or as complicated as you like. The ASP page merely needs to receive a single file and process it however you want with whatever component or native solution you use for file uploads. A: Yusuf - there doesn't seem to be a classic ASP version
{ "language": "en", "url": "https://stackoverflow.com/questions/7504737", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I hook into Rails *after* files are reloaded on each request in development mode? I'm working on a gem that sets properties on ActiveRecord models (such as table_name) dynamically based on a user config option. I have an initializer that achieves this. My problem however is that in dev mode, these classes are reloaded, so they don't maintain these values set. So I thought I'd use a railtie to hook into the point where these files are reloaded and run my config again on the models. My problem however is that config.to_prepare in the railtie appears to run before the reload! actually takes place. I can prove this with a bit of logging: module MyMod class Railtie < Rails::Railtie config.to_prepare do Rails.logger.debug("Contact object_id: #{Contact.object_id}") end end end if I load up my console, I get the first log: Contact object_id: 2202692040 If I check Contact.object_id it matches up: Contact.object_id #=> 2202692040 Then I reload! reload! Rails logger from my to_prepare logs: Contact object_id: 2202692040 So it still has the old object_id, but when I check it in the console: Contact.object_id #=> 2197355080 Which is the newly loaded class object id. So how do I get to_prepare to run after the files are reloaded? Using Rails 3.0.10 update I've also tried manually attaching this action to the after_prepare callback on the ActionDispatch::Callbacks like so: initializer "apartment.init" do ActionDispatch::Callbacks.set_callback(:prepare, :after) do Rails.logger.debug("Contact object_id: #{Contact.object_id}") end end It does indeed run the callback after the config.to_prepare but it still appears to happen before the files are reloaded... I get the same behaviour as above. A: Write an initializer that, if cache_classes is false, uses ActionDispatch::Reloader to set a to_prepare callback that runs your gem's installation routine. initializer 'foobar.install' do if Rails.configuration.cache_classes FooBar.install! else ActionDispatch::Reloader.to_prepare do FooBar.install! end end end It'll work both in the console with the reload! method and in the Rack application server. A: I believe the Rails reloader only unhooks the constants. The models are reloaded with autoloading when the constants are referenced in your app. In your callback, I think you have to trigger the load manually by referencing all the models. Maybe your gem can keep a list of all the models that include it, then just simply reference the constants to autoload them... model_names.each { |model_name| model_name.constantize } You can build the list with self.included: module MyGem self.included(base) @model_names ||= Set.new @model_names += base.to_s end end
{ "language": "en", "url": "https://stackoverflow.com/questions/7504744", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Managing lists and sublists with MySQL I am trying to create a database arrangement for the following scenario: Users of the site each have their own master list. This part is already being handled by one table that holds everyone's items, with a field that matches each user's unique idea. Each user will also be able to create any number of sub lists that are made up of the items from their master list. The order of the items in these lists will be editable, as well as the ability to insert some global values at certain points. This is the part I am stuck on. What would be the most efficient way to handle the sub lists? I've thought about creating a table of lists that are identified by user id and have a field of comma separated values that correspond to the items from the master list that the sub list is composed of, but I feel I would have a hard time keeping track of the item order that way. I have tried to search for this, but I am having trouble finding a way to phrase what I am trying to do in a searchable way. Also, if there are any recommendations for learning material that may help me come up with this answer on my own, I would love some recommendations. A: I would use a many-to-many table with an extra column. You'd have user_id, item_from_master_list_id, and position. That way you could select by user_id, and order by position.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504745", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Relations on composite keys using sqlalchemy I have this simple model of Author - Books and can't find a way to make firstName and lastName a composite key and use it in relation. Any ideas? from sqlalchemy import create_engine, ForeignKey, Column, String, Integer from sqlalchemy.orm import relationship, sessionmaker from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() engine = create_engine('mssql://user:pass@library') engine.echo = True session = sessionmaker(engine)() class Author(Base): __tablename__ = 'authors' firstName = Column(String(20), primary_key=True) lastName = Column(String(20), primary_key=True) books = relationship('Book', backref='author') class Book(Base): __tablename__ = 'books' title = Column(String(20), primary_key=True) author_firstName = Column(String(20), ForeignKey('authors.firstName')) author_lastName = Column(String(20), ForeignKey('authors.lastName')) A: The problem is that you have defined each of the dependent columns as foreign keys separately, when that's not really what you intend, you of course want a composite foreign key. Sqlalchemy is responding to this by saying (in a not very clear way), that it cannot guess which foreign key to use (firstName or lastName). The solution, declaring a composite foreign key, is a tad clunky in declarative, but still fairly obvious: class Book(Base): __tablename__ = 'books' title = Column(String(20), primary_key=True) author_firstName = Column(String(20)) author_lastName = Column(String(20)) __table_args__ = (ForeignKeyConstraint([author_firstName, author_lastName], [Author.firstName, Author.lastName]), {}) The important thing here is that the ForeignKey definitions are gone from the individual columns, and a ForeignKeyConstraint is added to a __table_args__ class variable. With this, the relationship defined on Author.books works just right.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504753", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "59" }
Q: Exporting mysql table to xml How can I export the contents of a mysql table to xml using php? I need this to de done and later on use this xml in a javacript application. The table is pretty simple an ID that is auto incremented , a name , a number , and a timestamp. I am using XAMPP 1.7.4 [PHP: 5.3.5] . And another question... where will the xml file be stored after it is created? A: If this is a one-off operation and you are okay with doing it manually, phpMyAdmin supports exports to various formats, including XML: http://wiki.phpmyadmin.net/pma/export. You get to chose the location of resulting file. If you have to do it programmatically, I suppose you'll have to run the mysqldump with the --xml flag from your script and read the resulting file (I'm pretty sure that's what phpMyAdmin does). Use the --tab option or I\O redirecting to create dump files where you want them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504754", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Custom html.tpl.php and other templates for a module/specific content type. (DRUPAL 7) Lets say I add this to my module: function example_preprocess(&$vars,$node) { $vars['theme_hook_suggestions'][] = 'example__page_'.$node; } Now every single item's theme gets overridden if I have a template. However, the template files I've placed in the module don't work, they're only used if I put them in the theme's template files. I'd like to distribute a template with my module, and have it work in any theme. Is that possible? A: I believe you need to use hook_theme to designate the template files your module includes. See the Using the theme layer (Drupal 6.x) handbook page for more details, under the Registering theme hooks and Implementing default templates sections.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504757", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C# - Looking for WebService Security like Spring Security Is there any way to secure Web Methods in c# like Spring Security Annotations? something like: public interface MyWebService { @Secured("ROLE_USER") public void delete(int cid); } Thanks A: Yes. Take a look at authorization for WCF. Specifically, the .Net analog for controlling security is with the PrincipalPermissionAttribute. For this to work, you will need to make sure your current context is associated with an identity, for instance, by requiring a username/password combination before connecting to your service and using those credentials to set the user account for the session.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504759", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Hudson is for unit testing or integration testing? Might be a basic question but I want to know does Hudson run Junit test cases or can be used to run integration test cases? A: Hudson, or more recently Jenkins, can be used to run whatever you want, whenever you want (e.g. on a schedule, or after each code check-in). You can run an Ant script, MSBuild file, shell script, batch script, a combination of these things.. anything. There is built-in support for displaying reports of your JUnit tests, but with over 400 plugins, you should be able to do what you need to.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504762", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: The type or namespace name 'LAD' could not be found (are you missing a using directive or an assembly reference?) Hello I have an ASP web application runs on C# as its backend that I'm trying to get running but the webpage (ran locally on my box) gives me the error message. Now the namespace the webapp is trying to reference is "using LAD.CDD.NSJ;" which are located in the App_Code folder. The name of the files are Common.cs, Email.cs, Data.cs, and User.cs. They all have a namespace call LAD.CDD.NSJ within the code. The previous programmers didn't make those files into a dll and just kept it as a .cs file. I'm trying to use these files for another project but keep getting that error message. A: The App_Code folder is a special folder in ASP.NET. ASP.NET will compile the types App_Code into an assembly which is actually separate from your web application assembly. This means, when you try and use those types from your backend code (e.g. an MVC controller), it is unable to resolve the type because those types will have a Build Action set to Content. With that build action, the file will not be included in the compilation of your main application. What I would recommend doing, is ditch using App_Code because simply changing the build action to Compile won't stop ASP.NET dynamically compiling an App_Code assembly, so you end up with ambiguous types (i.e., the runtime doesn't know whether to use the type compiled into your main application assembly, or the dynamic App_Code assembly. Move those files to another location, and set the Build Action (in Properties) to Compile.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504767", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: try server connection by evaluating server reply I am makeing a program in C# which needs to have a connection with a server. I'm building it with redundancy in order to eliminate server faults. Due to this, I'm having a textfile with server addresses which looks like this: 2011-09-21 18:01 http://server1.server.com http://server2.server.com http://server3.server.com The date is there to make sure the program has a fresh list of servers. The first thing it does when it starts, is to download this list and compare the date. If the downloaded file has a newer date, it replaces the older files. What I wan't to happen now, is that I want the program to read the file and make a list of possible servers (this is already done), and then iterate through the list to find a server that is giving the reply the server is expecting. Once the reply is gotten, it should stop checking and set the variable "server" to the server that just responded correctly. I have been trying with the following procedures, without any luck: int srvs = servers.Count(); int i = 0; string response = string.Empty; while (i < srvs) { var client = new WebClient(); try { response = client.DownloadString(servers[i] + "testcon.php"); } catch (WebException wex) { } finally { if (response == "OK") { server = servers[i]; } } if (servers.Contains(server)) break; i++; } This didn't work, it didn't stop the loop until it was at the end of the list. Next thing I tried, was this: var client = new WebClient(); foreach (string s in servers) { try { response = client.DownloadString(s + "testcon.php"); } catch (WebException wex) { } finally { if (response == "OK") server = s; } break; } How should I do to make it stop and set the server to the first server that is responding as expected (currently with "OK"). A: this: int srvs = servers.Count(); int i = 0; string response = string.Empty; while (i < srvs) { var client = new WebClient(); try { response = client.DownloadString(servers[i] + "testcon.php"); if (response == "OK") { server = servers[i];. break; } } catch (WebException wex) { } i++; } or this: var client = new WebClient(); foreach (string s in servers) { try { response = client.DownloadString(s + "testcon.php"); if (response == "OK") { server = s; break; } } catch (WebException wex) { } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7504775", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Need for a look up table? I have a people table and for each person I need to record category i.e. trainer, trainees, customer. Should I create a look up table for the above categories, or is it ok to put them as fileds in the people table? The db will be quite simple, so I think nulls are not a problem. A: Its highly recommended you have another table for category and make it a foreign key. This ensures that all the entries are in one of these categories, and if new categories comeup in future, you can easily append them to the category table A: If you only have a few people and you are sure you will never ever add more and never enhance anything then just do it like you want above and do self joins. If you want to make sure on standardized input for category, for example, you can hard code it or use the lookup table. You know your data better than I do so you will know what is right. Trust your instincts.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Graph Template Class I am working on Graph Template Class. Here is what I written till now. #ifndef __GRAPH_H__ #define __GRAPH_H__ #include <map> #include <list> template <typename _Ty> class Graph { private: template <typename _Ty> class Vertex { public: Vertex(_Ty in) : m_Label(in) { } ~Vertex() { } private: _Ty m_Label; protected: }; public: typedef Vertex<_Ty> VertexType; typedef std::list<VertexType> AdjListType; typedef std::map<VertexType,AdjListType> GraphType; public: Graph(bool bType = false) : m_Type(bType) { } ~Graph() { } void AddEdge(VertexType vLevt, VertexType vRight) { } private: // true if bidirectional // false if unidirectional. bool m_Type; GraphType m_Graph; protected: }; #endif Here is how I am using this class. #include "Graph.h" #include <string> int main(int argc, char **argv) { Graph<int> myGraph; myGraph.AddEdge(1,2); Graph<char *> myGraph2; myGraph2.AddEdge("A","B"); Graph<std::string> myGraph3; myGraph3.AddEdge("A","B"); } myGraph3 is giving me compilation error. error C2664: 'Graph<_Ty>::AddEdge' : cannot convert parameter 1 from 'const char [2]' to 'Graph<_Ty>::Vertex<_Ty>' Why this is error , if std::string test = "ABC"; works. A: That requires two implicit conversions * *First "A" needs to convert into std::string *Then std::string needs to convert into Vertex<std::string> (the nested type). That is chained-implicit-conversion which is not allowed. But when you write std::string test = "ABC", then only one conversion happens: char[4] to std::string. That is it. So the solution is, do one conversion yourself by explicitly passing std::string, and let the compiler do the other conversion: Graph<std::string> myGraph3; myGraph3.AddEdge(std::string("A"),std::string("B")); Now only one conversion is needed : std::string to Vertex<std::string>. Therefore, it will compile. A: std::string test = "ABC"; does implicit casting, but it is not happening while calling the function. Try myGraph3.AddEdge(std::string("A"),std::string("B"));. Function call overloading by defining another function as in void AddEdge(_Ty vLevt, _Ty vRight) { this->AddEdge((VertexType) vLevt, (VertexType) vRight); } helps. The other issue with your code (at least for gcc) is that you are using the same parameter _Ty in two nested template declarations. The complete, correct code, that works for me is: #include <map> #include <list> template <typename _Ty> class Graph { private: template <typename _Tyv> class Vertex { public: Vertex(_Tyv in) : m_Label(in) { } ~Vertex() { } private: _Tyv m_Label; protected: }; public: typedef Vertex<_Ty> VertexType; typedef std::list<VertexType> AdjListType; typedef std::map<VertexType,AdjListType> GraphType; public: Graph(bool bType = false) : m_Type(bType) { } ~Graph() { } void AddEdge(VertexType vLevt, VertexType vRight) { } void AddEdge(_Ty vLevt, _Ty vRight) { this->AddEdge((VertexType) vLevt, (VertexType) vRight); } private: // true if bidirectional // false if unidirectional. bool m_Type; GraphType m_Graph; protected: };
{ "language": "en", "url": "https://stackoverflow.com/questions/7504777", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Redirect from a TAB to a Website My developement team is creating diferent Tabs for one of our Facebook Brand Pages. These tabs are intended to redirect the user to specific sections in the company's website. I suggested that instead of automatically redirect the user we should add a message like: "You are being redirected to our company website" Im thinking about user experience and based on that i suggested this previous step, but the head of the developer unit says theres no reason to do that. I would like to hear your opinions on this matter, ¿should we inform the user that he is being redirected or should we redirect him automatically? Thank you very much for your help. A: So is the idea that when a user clicks on one of the tabs that they'll be redirected right then or there, or that something will show up in the tab from your website (like in an iframe)? I believe that redirecting the user after they click a tab is a bad idea. I hope these tabs will be FBML tabs with some text and links to direct the user where you want them to go, instead of redirecting the whole window away from Facebook on tab click.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504780", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How append a row line to an existing csv file using opencsv in java efficiently? I generate a csv file while adding lines row by row. In other words, I append lines one by one to the end of the file. I use opencsv to read and write the csv file. The problem is that i need to do some processing in order to have a new line. So what I am doing is reading the existing csv file (~6mb file) and addling one line and writing the file. So it is like the file was x. I am putting one more line, the file is now x+1. This involves of course many read and write operations. How can I do it efficiently. This is not a homework, neither a log file handling. It will be done couple of times, but needs to be done as fast as possible. Thanks. I already thought of creating the big csv file by creating x number of smaller csv files and then merging it. It doesn't seem to be efficient. Maybe it is stupid to ask, but is there any way of adding a new line without reading and the writing the complete data since the bottleneck is that it is getting slower and slower each time a new line is appended to the file. A: Why not just buffer your writes in a background thread (submit a bunch of lines, and whenever number > N or timeelapsed > T write to disk) Or do you always need an instantaneous consistent result? Also, you can normally APPEND with a SEEK (cheaper than reading the whole thing). Examples are RandomAccessFile object or FileOutputStream/FileWriter with append argument. That's still somewhat expensive of course. Finally, 6 MB isn't that big. Why not read it all in and write it lazily? Assuming this is a single JVM process, keeping it in memory is the easiest solution....
{ "language": "en", "url": "https://stackoverflow.com/questions/7504782", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CSS3 Gradients with background images?? Possible? Possible Duplicate: Is it possible to combine a background image and CSS3 gradients? I'm using CSS for a background gradient: background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #95d7d3), color-stop(1, #7db1ad) ); background:-moz-linear-gradient( center top, #95d7d3 5%, #7db1ad 100% ); filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#95d7d3', endColorstr='#7db1ad'); But I would also like to add a background image, is there a way of doing this with these gradients? If I use this: background: -moz-linear-gradient( center top, #95D7D3 5%, #7DB1AD 100% ) url(../img/icons.png) 0 -293px no-repeat!important; The gradient over-rides the background image. any ideas? A: background: url(../img/icons.png), -moz-linear-gradient( center top, #95D7D3 5%, #7DB1AD 100% ) ; A: Will the below link be helpful: http://css3.mikeplate.com/
{ "language": "en", "url": "https://stackoverflow.com/questions/7504784", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: checking existence of a ruby object and testing attributes of that object in one line Kind of a newbie question here but I promise it is really hard to google for. What I want to do is test the attribute of an object and test the existence of that same object in one line. I could do this: user = User.find_by_id(user_id) if user if user.access_token == params[:access_token] puts "success" else puts "failure" end else puts "failure" end I would like to seriously re-factor this and get rid of the nested if statements. Thing is, I can't do something like if user && user.access_token since in the case where user is actually nil, Ruby will throw an error when trying to evaluate nil.access_token. Anybody know the actual correct way to re-factor this into one line? Is it even possible, or are the nested if statements the only way? A: Doing user && user.access_token is fine since Ruby will stop evaluating the expression once it encounters one false condition. This is known as short circuit evaluation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504786", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Perl: Simple search and replace question I'm using ActiveState perl 5.12.4 on Windows 7. I'm trying to execute a search and replace … print "selected dir: $selected_dir basedir: $baseTestDir\n"; $selected_dir =~ s/$baseTestDir//g; Where $selected_dir = "\home\selenium\projects\myco\AutomatedTests\MyCliUSA\Critical Path\Live\G Sedan" and $baseTestDir = "\home\selenium\projects\myco\AutomatedTests\MyCliUSA". However, after the search and replace statement, $selected_dir is unchanged. How can I properly implement a search and replace here? A: You didn't convert the text in $baseTestDir into a regex pattern. This can be using quotemeta. my $base_test_dir_pat = quotemeta($base_test_dir); $selected_dir =~ s/^$base_test_dir_pat//; It's also accessible via \Q..\E in double-quoted and similar string literals. $selected_dir =~ s/^\Q$base_test_dir\E//; A trailing \E can be omitted. $selected_dir =~ s/^\Q$base_test_dir//; A: I would write the following to replace selected_dir with baseTestDir: $selected_dir =~ s/$selected_dir/$baseTestDir/; A: You need to escape the '\'s. Do $baseTestDir =~ s/\\/\\\\/g; before the replacement.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504787", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: When using the buildForm->add() function in Symfony2, What are the acceptable options? I have looked through the documentation and unless i've missed it I'm not able to find anything explaining what the official $options are for the buildForm->add() function in Symfony2. public function buildForm(FormBuilder $builder, array $options) { $builder->add('fieldname1'); $builder->add('fieldname2', new formObjectType(), $arrayOptions); } Taking the code above, what options would be passed in as an array for the second field. Thanks A: These options are passed to the field type, in your case formObjectType. So, it really depends on what options are accepeted by this field. For example, say you want to pass a option to tell the formObjectType to display or not a given field. You could do something like this: // Application/AcmeBundle/Form/Type/FormObjectType.php class FormObjectType extends AbstractType { public function buildForm(FormBuilder $builder, array $options) { $this->add('name', 'text'); if ($options['display_custom_field'] === true) { $this->add('name_custom', 'text'); } } public function getDefaultOptions(array $options) { return array( 'display_custom_field' => false, ); } } // Application/AcmeBundle/Controller/FormController.php class FormController extends Controller { public function createForm($object) { return $this->getFormFactory()->create(new FormObjectType(), $object, array( 'display_custom_field' => true, )); } public function customAction() { $form = $this->createForm(); // Code here ... } } If the option is the in the array passed or not array is passed at all, the default value if set in the formObjectType. So, this array is used to customize the options a given type is expected. This also work with built-in type like text, date, etc. Hope it helps. Regards, Matt P.S. You should start your class name with an upper case letter: FormObjectType instead of formObjectType to differentiate variables and methods from class names. This is only a suggestion :) A: This same question has bothered me as well. The default options are written inside respective type classes. Let's take DateType as an example. DateType::getDefaultOptions() lists all the default options, if you don't define them yourself. In addition we have DateType::getAllowedOptionValues() - it seems to define which values are valid for certain options. Note that all of the classes extend AbstractType and in addition to this inheritance every "type" implements FormTypeInterface::getParent(). For DateType the parent is FieldType. FieldType is obviously the parent class for most fields and it has a couple of default options defined as well. I'm guessing all these options get merged together upon calling out a specific form type.
{ "language": "en", "url": "https://stackoverflow.com/questions/7504792", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }