text
stringlengths
8
267k
meta
dict
Q: How does Tomcat maintain session integrity? HttpServletRequest's getSession(boolean) method mentions session integrity. How does Tomcat maintains session integrity? What rules does it use? What method? What is happening under the hood precisely? EDIT How and when is a specific session ID is created? Does Tomcat rely on IP address and port for example? A: In Tomcat the ManagerBase.generateSessionId() method is responsible for session id generation. It looks for me that session ids are generated based on random numbers. You can store the client's IP address in the session and check it in your webapp but as far as I know Tomcat does not do that. About session integrity: could you define it, please? There is a paragraph about it in the Java Servlet Specification, Version 3.0 but it isn't too much: 7.1.4 Session Integrity Web containers must be able to support the HTTP session while servicing HTTP requests from clients that do not support the use of cookies. To fulfill this requirement, Web containers commonly support the URL rewriting mechanism. A: This blog gives some details on Session Tracking with cookies with Tomcat.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573420", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Get and Setfocus of an element What I am trying to do is get the last focus element before doing a refresh on my BO and set it back to the last focus value. the idea is something like below: //get last focus element var x = Keyboard.FocusedElement; //refresh my businessobject here CallMethod(); //set the focus to my last element FocusManager.SetFocusedElement(focusScope, x); ... but the problem here is after calling the refresh object method my "x" value got changed in the process. Anyone experience this problem? A: You cannot just assign Keyboard.FocusedElement because Keyboard.FocusedElement is a reference type. So as soon as the Framework changes the Keyboard.FocusedElement, your copy changes. You will need to find a new way to identify the control that had focus before the call or try and find a deep copy solution that works. A: Why not use the Focus() method?? //get focused element UIElement x = Keyboard.FocusedElement as UIElement; //refresh my businessobject here CallMethod(); //set the focus to my last element x.Focus(); or consider using FocusManager.GetFocusedElement(focusScope)...
{ "language": "en", "url": "https://stackoverflow.com/questions/7573429", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to design a Tag table from another tables? I'm designing a software that will use tags to identify posts similar to StackOverflow, but with some differences. The tags must be loaded dinamically (like here), but come from various different tables because it will be used for identification. Example: the tag Brazil identifies an country in the country table, the tag Monday identifies a day in the week day table. I need an idea of how design this in the database. How have the tags from all tables loading, but identifying the correct table the data belongs. A: This might do what you want: CREATE TABLE countries ( name VARCHAR PRIMARY KEY, ... ); CREATE TABLE weekdays ( name VARCHAR PRIMARY KEY, ... ); CREATE VIEW tags AS (SELECT name AS tag, 'countries' AS source FROM countries) UNION ALL (SELECT name AS weekdays, 'weekdays' AS source FROM weekdays) UNION ALL ...; Then you can make additional tables and add them to the view. When you tag some other table, you'll treate the name and source of the tag as the primary key and refer to this view, like so: CREATE TABLE foo ( id SERIAL PRIMARY KEY, ... ); CREATE TABLE foo_tags ( foo_id INTEGER REFERENCES foo, tag_name VARCHAR, tag_source VARCHAR ); Unfortunately, it isn't possible to define a foreign key from the table foo_tags to the view tags defined above.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573430", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ext.Net LoadMode Merge due to lack of documentation about this feature i can't find a way to do this. I am trying to use autoLoad with merge mode. I have a TabPanel in which each tab is supposed to open autoloading another page using merge mode. i am aware that plain HTML does render, but pages including Ext.net components fail to render. In my child page i have a resource manager registered with RenderScripts set to 'None' Ext.Net examples page shows a merge mode example in that way. Right now i get a 'Ext.net.Store is not a constructor' in the child page. Is there any special parameter which needs to be sent in the loadConfig when doing the autoload? or are there any special elements besides resource manager needed on the child page? A: Using <AutoLoad Mode="Merge" /> is very tricky. In general I'd say it should be avoided, with preference given to using 'XRender' functionality or <AutoLoad Mode="IFrame" />. It's tough to say exactly what's going wrong in your code. Posting a simplified sample demonstrating how you have things configured and demonstrating how to reproduce the problem would be very helpful.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573435", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: IBrokers request Historical Futures Contract Data? I tried to request historical futures data but for a beginner the ibrokers.pdf document is not well enough documented. example Gold Miny Contract Dec11 NYSELIFFE: goldminy<-twsFuture("YG","NYSELIFFE","201112",multiplier="33.2") reqHistoricalData(conn, Contract= "goldminy", endDateTime"", barSize = "1 S", duration = "1 D", useRTH = "0", whatToShow = "TRADES","BID", "ASK", "BID_ASK", timeFormat = "1", tzone = "", verbose = TRUE, tickerId = "1", eventHistoricalData, file) I also don't know how to specify some of the data parameters correctly ? whatToShow ? i need Date,Time,BidSize,Bid,Ask,AskSize,Last,LastSize,Volume tickerID ? eventHistoricalData ? file ? A: I wrote the twsInstrument package (on RForge) to alleviate these sorts of headaches. getContract will find the contract for you if you give it anything reasonable. Any of these formats should work: "YG_Z1", "YG_Z11", "YGZ1", "YGZ11", "YGZ2011", "YGDEC2011", "YG_DEC2011", etc. (also you could use the conId, or give it an instrument object, or the name of an instrument object) > library(twsInstrument) > goldminy <- getContract("YG_Z1") Connected with clientId 100. Contract details request complete. Disconnected. > goldminy List of 16 $ conId : chr "42334455" $ symbol : chr "YG" $ sectype : chr "FUT" $ exch : chr "NYSELIFFE" $ primary : chr "" $ expiry : chr "20111228" $ strike : chr "0" $ currency : chr "USD" $ right : chr "" $ local : chr "YG DEC 11" $ multiplier : chr "33.2" $ combo_legs_desc: chr "" $ comboleg : chr "" $ include_expired: chr "0" $ secIdType : chr "" $ secId : chr "" I don't have a subscription to market data for NYSELIFFE, so I will use the Dec 2011 e-mini S&P future for the rest of this answer. You could get historical data like this tws <- twsConnect() hist.data <- reqHistoricalData(tws, getContract("ES_Z1")) This will give you back these columns, and it will all be 'TRADES' data > colnames(hist.data) [1] "ESZ1.Open" "ESZ1.High" "ESZ1.Low" "ESZ1.Close" "ESZ1.Volume" [6] "ESZ1.WAP" "ESZ1.hasGaps" "ESZ1.Count" whatToShow must be one of 'TRADES', 'BID', 'ASK', or 'BID_ASK'. If your request uses whatToShow='BID' then you will get the OHLC etc. of the BID prices. "BID_ASK" means that the Ask price will be used for the High and the Bid price will be used for the Low. Since you said the vignette was too advanced, it bears repeating that Interactive Brokers limits historical data requests to 6 every 60 seconds. So you should pause for 10 seconds between each request (or for getting lots of data I usually pause for 30 seconds after I make 3 requests so that if I have BID data for something I am also likely have ASK data for it) The function getBAT will download the BID, ASK and TRADES data, and merge together only the closing values of those into a single xts object that looks like this: > getBAT("ES_Z1") Connected with clientId 120. waiting for TWS reply on ES ............. done. Pausing 10 seconds between requests ... waiting for TWS reply on ES .... done. Pausing 10 seconds between requests ... waiting for TWS reply on ES .... done. Pausing 10 seconds between requests ... Disconnecting ... [1] "ES_Z1" > tail(ES_Z1) ES.Bid.Price ES.Ask.Price ES.Trade.Price ES.Mid.Price 2011-09-27 15:09:00 1170.25 1170.50 1170.50 1170.375 2011-09-27 15:10:00 1170.50 1170.75 1170.50 1170.625 2011-09-27 15:11:00 1171.25 1171.50 1171.25 1171.375 2011-09-27 15:12:00 1171.50 1171.75 1171.50 1171.625 2011-09-27 15:13:00 1171.25 1171.50 1171.25 1171.375 2011-09-27 15:14:00 1169.75 1170.00 1170.00 1169.875 ES.Volume 2011-09-27 15:09:00 6830 2011-09-27 15:10:00 4509 2011-09-27 15:11:00 4902 2011-09-27 15:12:00 6089 2011-09-27 15:13:00 6075 2011-09-27 15:14:00 14380 You asked for both LastSize and Volume. The "Volume" that getBAT returns is the total amount traded over the time of the bar. So, with 1 minute bars, it's the total volume that took place in that 1 minute. Here's an answer that doesn't use twsInstrument: I'm almost certain this will work, but as I said, I don't have the required market data subscription, so I can't test. reqHistoricalData(tws, twsFuture("YG","NYSELIFFE","201112")) Using the e-mini S&P again: > mydata <- reqHistoricalData(tws, twsFuture("ES","GLOBEX","201112"), barSize='1 min', duration='5 D', useRTH='0', whatToShow='TRADES') waiting for TWS reply on ES .... done. > head(mydata) ESZ1.Open ESZ1.High ESZ1.Low ESZ1.Close ESZ1.Volume ESZ1.WAP ESZ1.hasGaps ESZ1.Count 2011-09-21 15:30:00 1155.25 1156.25 1155.00 1155.75 3335 1155.50 0 607 2011-09-21 15:31:00 1155.75 1156.25 1155.50 1155.75 917 1155.95 0 164 2011-09-21 15:32:00 1155.75 1156.25 1155.50 1156.00 859 1155.90 0 168 2011-09-21 15:33:00 1156.00 1156.25 1155.50 1155.75 642 1155.83 0 134 2011-09-21 15:34:00 1155.50 1156.00 1155.25 1155.25 1768 1155.65 0 232 2011-09-21 15:35:00 1155.25 1155.75 1155.25 1155.25 479 1155.45 0 94 One of the problems with your attempt is that if you're using a barSize of '1 S', your duration cannot be greater than '60 S' See IB Historical Data Limitations
{ "language": "en", "url": "https://stackoverflow.com/questions/7573436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Common stack for some public variables Someone in stack-overflow answered "stack is attached to a thread, so when the thread exits the stack is reclaimed." But what about public variables how they are managed once thread execution is completed. For Ex. Declared public variable like public partial class Form1 : Form { int k = 10; private void button1_Click(object sender, EventArgs e) { k = k + 5; } } So in this whenever we click button1 a thread is created which updates value of k and then exist so as per this statement stack should be reclaimed and recent value of k should be lost but in reality it store that value and next button click will changes its retain value for ex. from 1) 10 to 15 2)15 to 20 3) 20 to 25 etc.... So My question is where such global variables are stored. Whether any other stack used for global variables. Also I will use object of a class inside a function for ex. such as public function add (int a, int b) { int c; clsitem objitem = new clsitem(); c=a+b + objitem.id; retun c; } so what will happened of objitem , whether it will store in stack and reclaimed when thread exits or it will stay in heap as it is an object A: In your example here, k is not a stack-based variable - it's a field of the Form1 class and is hence stored with the instance of the form. The two arguments to button1_click are examples of stack-based variables. A: Please take a look at this article which explains memory management and garbage collection of C#.NET http://csharpcomputing.com/Tutorials/Lesson6.htm
{ "language": "en", "url": "https://stackoverflow.com/questions/7573439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to determine file's extended attributes and resource forks with their size on Mac OSX? I had written a small utility for creating xml for any folder structure and comparison of folders via generated xml that supports both win and Mac as platforms. However on Mac, recursively calculating folder size don't adds up to total size. On investigation, it came that it is due to extended attributes and resource forks that were present on certain files. Can anybody know how can I determine these extended attributes and resource forks and their size preferably in python. Currently, I am using os.path.getsize to determine the size of file and adding files size to determine folder size eventually. A: Merely a partial answer ... but to learn the size of resource forks you can simply use the namedfork psuedodirectory os.path.getsize("<path to file of interest>/..namedfork/rsrc") Its theoretically possible that other named forks may exist ... but you can't discover a list of available forks. As to the extended attributes ... what "size" are you interested in? You can use the xattr module to discover their content and thus the length of the key/value pairs. But if you are interested more in their "on disk" size ... then its worth noting that extended attributes are not stored in some sort of file. They form part of the file metadata (ie just like the name and modified time are metadata) and are stored directly within a B*-tree node, rather than some "file" A: You want the hidden member of a stat result called st_blocks. >>> s = os.stat('some_file') >>> s posix.stat_result(st_mode=33261, st_ino=12583347, st_dev=234881026, st_nlink=1, st_uid=1000, st_gid=20, st_size=9889973, st_atime=1301371810, st_mtime=847731600, st_ctime=1301371422) >>> s.st_size / 1e6 # size of data fork only, in MB 9.889973 >>> x.st_blocks * 512e-6 # total size on disk, in MB 20.758528 The file in question has about 10 MB in the resource fork, which shows up in the result from stat but in a "hidden" attribute. (Bonus points for anyone who knows exactly which file this is.) Note that it is documented in man 2 stat that the st_blocks attribute always measures increments of 512 bytes. Note: st_size measures the number of bytes of data, but st_blocks measures size on disk including the overhead from partially used blocks. So, >>> open('file.txt', 'w').write('Hello, world!') 13 >>> s = os.stat('file.txt') >>> s.st_size 13 >>> s.st_blocks * 512 4096 Now if you do a "Get Info" in the Finder, you'll see that the file has: Size: 4 KB on disk (13 bytes) A: Two options: You could try using subprocess to call the system's "ls" or "du" command, which should be aware of the extended attributes. or You could install the xattr package, which can read the resource fork in addition to extended attributes (it's accessed via xattr.XATTR_RESOURCEFORK_NAME. Something like this might work: import xattr x = xattr.xattr("/path/to/my/file") size_ = 0 for attribute in x: size_ += len(x[attribute]) print size_ You might need to play around a little with the format of the extended attributes, as they're returned as strings but might be binary (?). If you provide a minimal almost working example of code, I might be able to play with it a little more.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573440", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Problem with encoding i have written my HTML code with the meta datas of meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" meta http-equiv="Content-Type" content="text/html; charset=utf-8" meta http-equiv="cache-control" content="NO-CACHE" meta http-equiv="content-language" content="pt" it is in UTF-8 format but when i opened this page in IE6 browser the encoding type is western european(ISO) so it shows portuguese language as informação originaly the string is informação what could be the problem please guide me A: The problem is IE6. Ask any web developer. Anyway, you'd better concentrate on newer browser versions, there's no use wasting your time with IE6 because you won't learn anything other than that it implements its own standards, which is absolutely not useful.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573445", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: OpenCL: multiple clEnqueueNDRangeKernel() calls I'm confused about how clEnqueueNDRangeKernel() works when called multiple times. Let's say I enqueue 10 times (for example, with a for loop), each time with global_work_size = 32. Let's say the kernel takes a global argument that it populates with get_global_id(0). My question is about the enumeration of the global_id's. What I expected: The highest-numbered global_id would be (10*32-1)=319. What actually happens: The highest-numbered global_id is (32-1)=31. Can anyone explain how each work item is enumerated, step-by-step, as multiple clEnqueueNDRangeKernel() calls are made? A: The NDRange space created in each clEnqueueNDRAngeKernel call is independent of each other, the global work item IDs is not consecutive or related at all between each call.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573446", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What's a good way to mimic Web Forms RadioButtonList in ASP.NET MVC? I have View Model List like this: public class PersonViewModel { int PersonId bool LikesIceCream } The View will display a list of people and their preference to ice cream - like it or don't. I'm not sure how to construct the html in a way that I can use the RadioButtonFor HTML helper and properly pass the values back to the controller. Simply creating RadioButtonFor's in a foreach loop doesn't help because they will have the same name. Any idea how I can hook these values up with the model binder? Thanks. A: View model: public class PersonViewModel { public int PersonId { get; set; } public bool LikesIceCream { get; set; } } Controller: public class HomeController : Controller { public ActionResult Index() { var model = new[] { new PersonViewModel { PersonId = 1, LikesIceCream = true }, new PersonViewModel { PersonId = 2, LikesIceCream = false }, new PersonViewModel { PersonId = 3, LikesIceCream = true }, }; return View(model); } [HttpPost] public ActionResult Index(IEnumerable<PersonViewModel> model) { // you will get what you need here inside the model return View(model); } } View (~/Views/Home/Index.cshtml): @model IEnumerable<PersonViewModel> @using (Html.BeginForm()) { @Html.EditorForModel() <input type="submit" value="OK" /> } Editor template (~/Views/Home/EditorTemplates/PersonViewModel.cshtml): @model PersonViewModel <div> @Html.HiddenFor(x => x.PersonId) @Html.RadioButtonFor(x => x.LikesIceCream, "true") Yes @Html.RadioButtonFor(x => x.LikesIceCream, "false") No </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/7573451", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: .NET 2.0 App.Config connection strings includes unwanted SQLExpress default I'm using a connectionStrings section within an app.config file in a .NET 2.0 project. The config section contains two connection strings I have defined. When I retrieve the ConnectionStringSettingsCollection it has a count of 3. The 0th entry is a connection to SQLExpress Name: LocalSqlServer, ConnectionString: data source=.\\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true Why is this connection being included even though it's not in my app.config, and how can I get rid of it? This code will be running on desktop machines that I have no access to - so how can I prevent any more local connections from randomly showing up at runtime? I can't see any properties on the connection that indicate it's any different from the two I defined. A: It's defined in machine.config. To get rid of it, use: <connectionStrings> <clear/> <add ... > </connectionStrings> As a general rule, sections that have <add> and <remove> elements (e.g. appSettings, connectionStrings and the provider configuration sections) also have a <clear> element, which you can use if you don't want to inherit elements from a higher level web.config or machine.config file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573453", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: XSLT Help getting Distinct values I have an XML document (shown below), what I need to do is get a list of all the unique Type @ID values, regardless of where they are below SizeRanges So for this document I need to get 10,8,6,5 into something I can use for-each upon. Ultimately, I'm trying to show each SizeRange in a table beside each other, and get the same Types to line up on the same row. But the problem I am having is extracting a distinct list of Types I can loop on. XML Document: <SizeRanges> <SizeRange ID="1" Name="8-18"> <Types> <Type ID="10"> <Size Name="8" Quantity="1" /> <Size Name="10" Quantity="2" /> <Size Name="12" Quantity="2" /> <Size Name="14" Quantity="3" /> <Size Name="16" Quantity="1" /> <Size Name="18" Quantity="1" /> </Type> <Type ID="8"> <Size Name="8" Quantity="1" /> <Size Name="10" Quantity="1" /> <Size Name="12" Quantity="2" /> <Size Name="14" Quantity="2" /> <Size Name="16" Quantity="1" /> <Size Name="18" Quantity="1" /> </Type> <Type ID="6"> <Size Name="8" Quantity="1" /> <Size Name="10" Quantity="1" /> <Size Name="12" Quantity="1" /> <Size Name="14" Quantity="1" /> <Size Name="16" Quantity="1" /> <Size Name="18" Quantity="1" /> </Type> <Type ID="5"> <Size Name="10" Quantity="1" /> <Size Name="12" Quantity="1" /> <Size Name="14" Quantity="1" /> <Size Name="16" Quantity="1" /> <Size Name="18" Quantity="1" /> </Type> </Types> </SizeRange> <SizeRange ID="2" Name="S-XL"> <Types> <Type ID="10"> <Size Name="S" Quantity="1" /> <Size Name="M" Quantity="3" /> <Size Name="L" Quantity="4" /> <Size Name="XL" Quantity="2" /> </Type> <Type ID="8"> <Size Name="S" Quantity="1" /> <Size Name="M" Quantity="2" /> <Size Name="L" Quantity="3" /> <Size Name="XL" Quantity="2" /> </Type> <Type ID="6"> <Size Name="S" Quantity="1" /> <Size Name="M" Quantity="2" /> <Size Name="L" Quantity="2" /> <Size Name="XL" Quantity="1" /> </Type> <Type ID="5"> <Size Name="S" Quantity="1" /> <Size Name="M" Quantity="1" /> <Size Name="L" Quantity="2" /> <Size Name="XL" Quantity="1" /> </Type> </Types> </SizeRange> </SizeRanges> A: Give this a shot: <xsl:key name="types" match="Type" use="@ID"/> <xsl:variable name="distinctTypes" as="xs:integer*" select="distinct-values(//SizeRange/Types/Type)" /> <xsl:template match="/"> <xsl:for-each select="$distinctTypes"> <xsl:value-of select="." /> </xsl:for-each> </xsl:template> Here's another way: <xsl:key name="types" match="Type" use="@ID"/> <xsl:template match="/"> <xsl:for-each select="//SizeRange/Types/Type[generate-id() = generate-id(key('types', @ID)[1])]"> <xsl:value-of select="@ID"/> </xsl:for-each> </xsl:template> A: on XSLT 2.0, you can do this way.. distinct-values(/SizeRanges/SizeRange/Types/Type/@ID) This gives unique ID's as output
{ "language": "en", "url": "https://stackoverflow.com/questions/7573459", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is Cache-Control:must-revalidate obliging to validate all requests, or just the stale ones? I have a mess with this header, I have read that Cache-Control:must-revalidate oblige to validate all requests with the source before serving a cached item, but just the stale ones? or all no matter if stale or fresh? I have read both things in different places. What is the difference with Cache-Control:no-cache ? Because these headers look equivalent to me. UPDATE 1: I have read this from a book: The Cache-Control: must-revalidate response header tells the cache to bypass the freshness calculation mechanisms and revalidate on every access: @Peter O. has pointed out what the RFC says. So that old book is wrong. UPDATE 2: In this tutorial : http://www.mnot.net/cache_docs/ no-cache — forces caches to submit the request to the origin server for validation before releasing a cached copy, every time. This is useful to assure that authentication is respected (in combination with public), or to maintain rigid freshness, without sacrificing all of the benefits of caching. must-revalidate — tells caches that they must obey any freshness information you give them about a representation. HTTP allows caches to serve stale representations under special conditions; by specifying this header, you’re telling the cache that you want it to strictly follow your rules. A: Section 14.9.4 of HTTP/1.1: When the must-revalidate directive is present in a response received by a cache, that cache MUST NOT use the entry after it becomes stale to respond to a subsequent request without first revalidating it with the origin server Section 14.8 of HTTP/1.1: If the response includes the "must-revalidate" cache-control directive, the cache MAY use that response in replying to a subsequent request. But if the response is stale, all caches MUST first revalidate it with the origin server... So it appears that only stale responses must be revalidated if must-revalidate is received. For no-cache, see section 14.9.1: If the no-cache directive does not specify a field-name [which is the case here], then a cache MUST NOT use the response to satisfy a subsequent request without successful revalidation with the origin server... Thus, no-cache applies both to fresh and stale responses. EDIT: This phrase may be relevant here (section 13.3): When a cache has a stale entry that it would like to use as a response to a client's request, it first has to check with the origin server (or possibly an intermediate cache with a fresh response) to see if its cached entry is still usable. So, must-revalidate is probably relevant when the cache has intermediate caches, since otherwise the cache can check the intermediate cache for a fresh response rather than check the origin server directly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573466", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: RSACryptoServiceProvider - Value cannot be null - rgb My DNN module encrypts some data using my public key and presents it to the user. The user submits this data to me for processing. I decrypt the data with my private key and use it. I use the .Net RSACryptoServiceProvider for encryption/decryption. This has worked well till now. I received some data from a customer, which throws an error when I attempt to decrypt it - Value cannot be null. Parameter name: rgb Since the encryption is happening on the user's server, I was wondering if there are any environmental factors that could affect it. I am really not sure how to proceed with narrowing down the problem. What makes the same code behave differently on a different server? I can provide any other information required. Any input appreciated. Thanks. Edit: Added Stacktrace System.ArgumentNullException: Value cannot be null. Parameter name: rgb at System.Security.Cryptography.RSACryptoServiceProvider.Decrypt(Byte[] rgb, Boolean fOAEP) at MyWS.MyMethod(String param1, String EncryptedData, String& errMsg) --- End of inner exception stack trace --- A: It turns out to be the most basic problem - Wrong User Input. :( Well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573468", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Apache POI - background colours not as expected Thanks for looking. Im using Apache POI to read an excel file. I want to use conditional logic that will use background colour. But I don't understand the results Im getting. Why does following code show different results for same colours? Code: XSSFCell cell = (XSSFCell) row.getCell(i); if(cell.getDateCellValue()!=null) { DateTime val = new DateTime(cell.getDateCellValue()); //Joda-Time lib. XSSFCellStyle cellStyle = (XSSFCellStyle) cell.getCellStyle().clone(); cellStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND); XSSFColor x = cellStyle.getFillForegroundXSSFColor(); String colorStrVal = x==null ? "null" : x.getARGBHex() + ":" + x.getIndexed(); System.out.println(val.toString("dd/MM/yyyy") + " - " + colorStrVal); } Results - I expect non-specified colour entries to all be same (they are grey and look fine in excel - all register as same colour): 06/04/2007 - FFFFFFFF:0 02/06/2008 - FFFFFFFF:0 10/05/2011 - FFFFF2B9:0 //yellow 26/07/2008 - FFFFFFFF:0 04/07/2010 - FFFFFFFF:0 12/04/2009 - FFFFFFFF:0 19/09/2010 - FFFFFFFF:0 16/04/2011 - FFFFFFFF:0 16/01/2009 - FFFFFFFF:0 16/06/2010 - FFD9D9D9:0 14/05/2011 - FFD9D9D9:0 07/12/2007 - FFFFFFFF:0 22/02/2009 - FFFFFFFF:0 25/10/2009 - FFFFFFFF:0 11/08/2008 - FFFFFFFF:0 29/10/2009 - FFFFFFFF:0 06/09/2010 - FFFFFFFF:0 24/06/2011 - FFE60000:0 //red 15/08/2008 - FFFFFFFF:0 17/09/2010 - FFFFFFFF:0 27/03/2011 - FFFFFFFF:0 19/05/2008 - FFFFFFFF:0 26/05/2009 - FFFFFFFF:0 03/09/2010 - FFFFFFFF:0 25/04/2011 - null //white 22/06/2011 - FFFFF2B9:0 //yellow 25/09/2009 - FFFFFFFF:0 20/04/2011 - FFFFFFFF:0 16/06/2011 - FFFFF2B9:0 //yellow 02/03/2010 - FFD9D9D9:0 31/01/2011 - FFD9D9D9:0 03/06/2011 - FFFFF2B9:0 //yellow 03/07/2010 - FFFFFFFF:0 12/09/2010 - FFFFFFFF:0 14/11/2010 - FFE60000:0 //red 23/06/2011 - FFFFF2B9:0 //yellow 24/06/2011 - FFFFF2B9:0 //yellow 18/09/2010 - FFD9D9D9:0 11/03/2011 - FFD9D9D9:0 25/12/2010 - null //white 17/05/2011 - FFEEECE1:0 //blue 27/03/2010 - FFFFFFFF:0 12/03/2011 - FFFFFFFF:0 14/03/2011 - FFFFFFFF:0 A: Promoting Comment of OP: Thanks for pointing me in right direction. I unziped and looked at the styles.xml. Could see some elements with with tint values. When I now get the tint value in poi the grey cells above show as: 06/04/2007 - FFFFFFFF:0:-0.1499984740745262 I can rely on poi now :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7573472", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I set up TinyMCE so that it won't allow inline data images? I have a TinyMCE installation on a CMS and the users have been pasting in images which are of the inline data type. This kind of thing: <img src="data:image/gif;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub/ /ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcpp V0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7" width="16" height="14" alt="embedded folder icon"> They are pasting in some pretty large images, and the content gets stored in a database. This is making the database grow very quickly in size, and there is already a media upload component available, so how can I simply prevent the editor from accepting this type of image? A: This depends on what you want. Due to the fact that you won't be able to disallow this kind of element using valid_elements and child_elements you will have to go other ways. Case 1: You do not want user to enter this kind of image onPaste. You will need to use the paste plugin and set the parameter paste_pre paste_preprocess : function(pl, o) { window.console && console.log('Object', o); window.console && console.log('Content:', o.content); // modify o.content here -> remove images of that kind o.content = o.content.substr(...) } Case 2: You want the images to be filtered out before they are getting saved into the DB. You may use the tinymce setup paramter combined with onSave to get rid of them. From what you describe you seem to be wanting Case 1.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573474", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Copy to clipboard without System.Windows.Forms.Clipboard? Well the question is that. Is there anyway to copy text and/or files to the Windows clipboard WITHOUT using Clipboard Class from .NET? A: Depends on if I am answering the question in the title or in the text... you can access System.Windows.Clipboard without having access to System.Windows.Forms... string textData = "I want to put this string on the clipboard."; // After this call, the data (string) is placed on the clipboard and tagged // with a data format of "Text". System.Windows.Clipboard.SetData(DataFormats.Text, (Object)textData);
{ "language": "en", "url": "https://stackoverflow.com/questions/7573482", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: EXC_BAD_ACCESS on calling drawRect on a retained UIImage I have a bit of a weird problem. I create a UIImage with imageNamed extract colour data from it and then set it to another class. Then from that class when I do a drawRect I get an EXC_BAD_ACCESS when doing the drawRect. Here is where I load the image: UIImage* pImageHM = [UIImage imageNamed:@"Heatmap2.png"]; CGImageRef irHM = [pImageHM CGImage]; CFDataRef drHM = CGDataProviderCopyData( CGImageGetDataProvider( irHM ) ); R8G8B8A8* pDataHM = (R8G8B8A8*)CFDataGetBytePtr( drHM ); unsigned int colour = 0; unsigned int colourMax = 256; while( colour < colourMax ) { // Extract image data. colour++; } [mpView SetScale: pImageHM]; CFRelease( drHM ); CGImageRelease( irHM ); The SetScale function is defined as follows: - (void) SetScale: (UIImage*)pImage { [mpScale release]; mpScale = pImage; [mpScale retain]; [self setNeedsDisplay]; } And finally I render it as follows: CGContextRotateCTM( ctx, -M_PI_2 ); CGContextTranslateCTM( ctx, -(rect.size.height - 48), 0); [mpScale drawInRect: CGRectMake( 0, rect.size.width - 16, rect.size.height - 48, 16 )]; CGContextTranslateCTM( ctx, (rect.size.height - 48), 0 ); CGContextRotateCTM( ctx, M_PI_2 ); Why would the mpScale raise an EXC_BAD_ACCESS? Given the UIImage has been retained the fact it was subsequently autoreleased after I had called SetScale should be neither here nor there. I should add that if I don't call SetScale (such that mpScale remains as nil) then I get no crash and, obviously, I don't see anything where the scale ought to be. Thanks in advance! A: CGImageRef irHM = [pImageHM CGImage]; You do not own this CGImage, but you are releasing it. CGImageRelease( irHM ); A: You have multiple problems here: * *Your SetScale method does not follow Cocoa naming conventions (see here). Call it setScale with a lowercase "set" prefix, for it to be considered as a setter (and hence allow KVC to work, dot-notation to work automatically, etc) *You have to check that mpImage and pImage are not the same object when implementing the setScale setter. If you don't you will end up with an EXC_BAD_ACCESS (maybe the one you have, then) because you will release the object before affecting+retaining it so it will reach a retainCount of zero before you have a chance to retain it again. Your setter should be: -(void)setScale:(UIImage*)pImage { // only do this if the variables don't point to the same object in memory to avoid crash if (mpImage != pImage) { [mpImage release]; // release old value mpImage = [pImage retain]; // retain new one } } Moreover (and this is the real reason of your EXC_BAD_ACCESS), you are releasing irHM (CGImageRelease on the last line of your code) but you shouldn't (you didn't retain it or take ownership of it before) CGImageRef irHM = [pImageHM CGImage]; CFDataRef drHM = CGDataProviderCopyData( CGImageGetDataProvider( irHM ) ); ... [mpView SetScale: pImageHM]; CFRelease( drHM ); // <-- that's ok because you did use a "...Copy..." method // CGImageRelease( irHM ); // <-- you DON'T need nor should do that !! A: In the event pImage == mpScale, when you call SetScale you will release the image, set it, then retain nothing. mpScale at that point will be pointing to an invalid object.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573489", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: is there a free php forum with pluggable encryption, or something better than just an md5 hash? it seems like phpbb, mybb, and vbulletin and others i come across all use md5. i'd like to do integration with my main site's authentication with something more secure (sha or just the builtin crypt('password', "$salt")), but don't want to hack up a dependency to pieces so it becomes difficult to upgrade. Any ideas? A: What's wrong with MD5? This is what's wrong: MD5 + one salt + another salt applied to a six-character password is breakable these days, with current PC hardware, in seconds, just by brute force alone. Have a look at this SO discussion and also at this one here. Then google bcrypt and glance at some of the references. MD5 just does not do it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573491", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Div to show and stay on mouse hover - Stays up even when mouseout I've been playing around with several ways of hover divs, but most of the methods I tested only stay up when the mouse is hovering over the link. What I want to achieve is for the div to appear on hover of another div, but stays up even when the mouse leaves the div button. An example would be: http://www.prixtel.com/ I don't mind if it's just CSS or mixed with Jquery/JS. Thank you! My sample: http://jsfiddle.net/h4rB9/1/ A: Bind the event that makes the div visible (turning off display: none or whatever) to the mouseover event using something like the jQuery .mouseover() bind. If you don't specify a .mouseout() bind then it won't go away. A: That website is using script for that effect. If you want to use JavaScript: var myDiv = document.getElementById("myDiv"); if (document.addEventListener) { myDiv.addEventListener("mouseover", function () { // whatever it is you're doing on mouseover here }, false); } else if (document.attachEvent) { myDiv.attachEvent("onmouseenter", function () { // whatever it is you're doing on mouseover here }); } else { myDiv.onmouseover = function () { // whatever it is you're doing on mouseover here } } jQuery: // I prefer mouseenter to mouseover, and jQuery lets you do that as does IE with attachEvent $("#myDiv").mouseenter(function () { // whatever it is you're doing on mouseover here }); As the other poster noted, the key is to omit the mouseout event - using hover automatically includes the mouseout behavior.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573492", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: KeyEvent.KEYCODE_MEDIA_NEXT not received unless audio is playing I've paired with a Bluetooth headset. When audio is playing, KeyEvent.KEYCODE_MEDIA_NEXT and KeyEvent.KEYCODE_MEDIA_PREVIOUS are received fine in my BroadcastReceiver. When audio is not playing, my receiver does not get called for these key events. In this same state, when audio is not playing, this same receiver is called for play/pause, KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE, so I know this is not an issue of my receiver not being registered. Once audio does begin to play, I can see via logs that while audio was not playing, all KeyEvent.KEYCODE_MEDIA_NEXT events were queued, and are re-delivered once audio starts. Each of these events is delivered with KeyEvent.ACTION_DOWN. Is this normal behavior? Do Bluetooth next and previous buttons only function when audio is playing? A: I have met the same issue with one pair of headphones. But when I tried another pair of headphones my BroadcastReceiver received KEYCODE_MEDIA_PREVIOUS and KEYCODE_MEDIA_NEXT, when audio was NOT playing. So it seems that the issue depends on the headphones you're using.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573493", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Seg Fault while trying to fill in a matrix contained in a struct I've got a structure for a matrix : struct Matrice{ int nblig; int nbcol; int **mat; }; And my program's got a seg fault when i try to fill the matrix : void initMat(Matrice *M) { int j, i; srand(time(0)); M->nbcol = (rand()%5)+1; M->nblig = (rand()%5)+1; for(i=0; i<M->nbcol;i++){ for(j=0; j<M->nblig;j++){ M->mat = rand()%101; //segfault here } } } It's been a while i've not practised C, anyone got a clue on why i've got this segfault? Thanks. A: I find it hard to believe that the program segfaults exactly at that line, but it's quite likely that it will segfault at some time if you assign a random value to a pointer. You should allocate memory for the matrix using malloc; multiple times, in fact, if you use a double pointer structure. When handling matrices in C, I tend to use a different structure: struct Matrix { size_t ncols, nrows; int *mat; }; then initialize the mat member with malloc(ncols * nrows) and index with mat[i * nrows + j]. The indexing is a bit harder, but the memory management is a lot easier and some matrix operations likely become a lot faster because everything is stored in one array. A: You need to initialize the mat member into a two-dimensional array of the appropriate number of rows and columns. void initMat(Matrice *M) { int j, i; srand(time(0)); M->nbcol = (rand()%5)+1; M->nblig = (rand()%5)+1; M->mat = malloc(nbcol * sizeof(int)); if (!M->mat) { /* memory allocation failed */ } for(i=0; i<M->nbcol;i++){ M->mat[i] = malloc(nblig * sizeof(int)); if (!M->mat[i]) { /* memory allocation failed */ } for(j=0; j<M->nblig;j++){ M->mat[i][j] = rand()%101; } } } You need to #include <stdlib.h> in order to have (warning-free) access to the malloc function. A: It looks like you're trying to assign a number to mat. There are two things that look wrong with this: - You need to allocate memory for mat. Right now you have a pointer there, but by default it doesn't point to anything. - You're assigning to mat directly, treating it like a single integer. If it's supposed to be a matrix, you probably want to index based off of it (like M->mat[i][j]). Allocate the memory first, though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573503", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dynamic Content into mail() $message I'm just trying to put together a simple HTML email confirming an order to my database. My $message looks a little like: $message = " <html> <head> <title>Whatever</title> </head> <body> etc etc </body> </html> "; What i want to do within the $message HTML is make a call to my database which will return rows something like: $emailinfo=mysql_fetch_assoc($result) or die(mysql_error()); To which i can then use in my $message along the lines of: <p><?php echo $emailinfo['customername'];?></p> There's nothing wrong with my query or my tables etc, the problem i'm having and need help with is getting the results from mysql_fetch_assoc into my $message html. Can anyone help? Thanks Dan A: You can do something like this: Example: $message = <<<END <html> <head> <title>Whatever</title> </head> <body> <p>{$emailinfo['customername']}</p> </body> </html> END; There are several other ways to achieve this. For more information, see http://php.net/manual/en/language.types.string.php. Loop example: <?php while ( $emailinfo = mysql_fetch_assoc($result) ) { // The "END;" must be at the start of the line (e.g. no white spaces before it). $message = <<<END <html> <head> <title>Whatever</title> </head> <body> <p>{$emailinfo['customername']}</p> </body> </html> END; echo $message; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7573505", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Changing cursor when rendering a JList I've achieved what I'm trying to do, but I can't help but to think there is a more efficient way...allow me to illustrate. In short, the question I'm asking is if there's a way to determine when a component has finished it's initial rendering. I have a JList, which is hooked up to a DefaultListModel and getting painted by a custom renderer which extends the DefaultListCellRenderer. This intention of the JList is to "page" through a log file, populating 2500 elements every time a new page is loaded. On my machine it usually takes a couple seconds to fully render the JList, which is not really a problem because changing the cursor to a wait cursor would be acceptable because it would give the user immediate feedback. Unfortunately, I cannot figure out an elegant way to know when the initial rendering has completed. Below is the code of my renderer, in it you'll see I'm counting the number of iterations on the renderer. If that is between 0 and N-20, the cursor changes to a wait cursor. Once N-20 has been reached, it reverts back to a default cursor. Like I previously mentioned, this works just fine, but the solution really feels like a hack. I've implemented the ListDataListener of the DefaultListModel and the PropertyChangeListener of the JList, but neither produce the functionality I'm looking for. /** * Renders the MessageHistory List based on the search text and processed events */ public class MessageListRenderer extends DefaultListCellRenderer { private static final long serialVersionUID = 1L; String lineCountWidth = Integer.toString(Integer.toString(m_MaxLineCount).length()); @Override public Component getListCellRendererComponent(JList l, Object value, int index, boolean isSelected, boolean haveFocus) { JLabel retVal = (JLabel)super.getListCellRendererComponent(l, value, index, isSelected, haveFocus); retVal.setText(formatListBoxOutput((String)value, index)); // initial rendering is beginning - change the cursor if ((renderCounter == 0) && !renderCursorIsWait) { m_This.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); renderCursorIsWait = true; } // initial rendering is complete - change the cursor back if ((renderCounter > (l.getModel().getSize() - 20)) && renderCursorIsWait) { m_This.setCursor(Cursor.getDefaultCursor()); renderCursorIsWait = false; } renderCounter++; return retVal; } /** * Adds font tags (marks as red) around all values which match the search criteria * * @param lineValue string to search in * @param lineIndex line number being processed * @return string containing the markup */ private String formatListBoxOutput(String lineValue, int lineIndex) { // Theoretically the count should never be zero or less, but this will avoid an exception just in case if (m_MaxLineCount <= 0) return lineValue; String formattedLineNumber = String.format("%" + Integer.toString(Integer.toString(m_MaxLineCount).length()) + "s", m_CurrentPage.getStartLineNumber() + lineIndex) + ": "; // We're not searching, simply return the line plus the added line number if((m_lastSearchText == null) || m_lastSearchText.isEmpty()) return "<html><font color=\"#4682B4\">" + formattedLineNumber.replaceAll(" ", "&nbsp;") + "</font>" + lineValue + "</html>"; // break up the search string by the search value in case there are multiple entries String outText = ""; String[] listValues = lineValue.split(m_lastSearchText); if(listValues.length > 1) { // HTML gets rid of the preceding whitespace, so change it to the HTML code outText = "<html><font color=\"#4682B4\">" + formattedLineNumber.replaceAll(" ", "&nbsp;") + "</font>"; for(int i = 0; i < listValues.length; i++) { outText += listValues[i]; if(i + 1 < listValues.length) outText += "<font color=\"red\">" + m_lastSearchText + "</font>"; } return outText + "</html>"; } return "<html><font color=\"#4682B4\">" + formattedLineNumber.replaceAll(" ", "&nbsp;") + "</font>" + lineValue + "</html>"; } } All I'm doing to populate the model is this: // reset the rendering counter this.renderCounter = 0; // Reset the message history and add all new values this.modelLogFileData.clear(); for (int i = 0; i < this.m_CurrentPage.getLines().size(); i++) this.modelLogFileData.addElement(this.m_CurrentPage.getLines().elementAt(i)); A: In addition to @mKorbel suggestions, use a SwingWorker to fill the list model in batches. Add a property change listener to the worker and restore the cursor when done. There's a related Q&A here. private static class TaskListener implements PropertyChangeListener { @Override public void propertyChange(PropertyChangeEvent e) { if (e.getNewValue() == SwingWorker.StateValue.DONE) { // restore cursor } } } A: 1) you have add Cursor to the JList, not inside Renderer, example here or here 2) Renderer by default returns JLabel, there isn't special reason for defining that 3) Renderer can setBackground, Font whatever methods for (in this case) the JLabel EDIT: 4) remove retVal.setText(formatListBoxOutput((String)value, index)); create DefaulListModel and move prepared Items to the Model#addItem 5) int index, can compare with JList#getModel().getSize() -1; remove that from Renderer, 6) better would be add your Items from BackGround Task (@trashgod your suggestion was right:-) and fill in batches (thank you), if you'll implemnts SwingWorker, then you can create batch at 50 Items and adding by 50... until done 7) Renderer is only for formating output, your Html formating could be: * *removed, rest see in point 3th. *prepared in BackGroung Task instead of built constructor between Renderer and loading + Html Formating + Backward interactions to the Renderer, in this case is Renderer useless, because you can pertty pre-formating Items that by using Html, then remove Renderer
{ "language": "en", "url": "https://stackoverflow.com/questions/7573508", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to make session/cookies work in all subdomains in Yii I have several subdomains like 'a.domain.com','b.domain.com' but I found that if i login at subdomain a, session/cookies won't work in b, and i have to login again in 'b.domain.com' How do I make login session work in all subdomains? Update: I found each subdomain has a different session id... Update: I found I could only login in several domians like 'bench' and 'post', but cannot login in 'book' and other domains. Really strange. A: You could set it in yii config/main.php file, like i did. (i'm not sure if you still have to change php.ini file, but i would say "no", because this configuration below fixed my problem). protected/config/main.php ... 'components' => array( ... 'user'=>array( ... 'identityCookie' => array('domain' => '.mydomain.com', //note dot before domain name // identityCookie same as "session->cookieParams->domain" ), 'session' => array( 'autoStart'=>true, 'cookieParams' => array('domain' => '.mydomain.com'), ), ... ) ... A: You could use PHP's session.cookie_domain value and set it to your top level domain (.domain.com). By editing php.ini or setting using ini_set('session.cookie_domain', '.domain.com'); Good luck :) Shai.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573515", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Private _Accessors don't build with MSBUILD I have a build script (.bat) that invokes MSBUILD (C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\msbuild.exe) that used to work for a while but stopped working after I installed VS11 Developer Preview. Now, the build is not able to rebuild projects that include MSTest unit tests with private accessors. I am getting error CS0246: The type or namespace name 'BaseViewModel_Accessor' could not be found (are you missing a using directive or an assembly reference?) which pretty much means that MSBuild refuses to auto-generate the BaseViewModel_Accessor assembly. Of course, BaseViewModel is just an example - I am getting the error for every test class that requires accessors. Those very same projects build just fine on the same machine from within Visual Studio 2010 (but not VS11). I am aware of at least one answer to this question, but it is somewhat unsatisfactory, as VS is obviously installed on my machine, and I am not using NUnit but Microsoft's very own unit testing framework. I suspect that the observed behavior might have to do with the fact that VS11 is a "Developer Preview" (my VS10 is Ultimate), so it may be crippled and not able to generate the accessors. However, I am explicitly using .NET 4 MSBUILD.exe and so expecting it to be able to use whatever VS10 is using internally... Anyway, if someone has any less invasive solutions than to remove both Visual Studio installations and .NET 4.5, and re-install everything from scratch, they would be much appreciated. There's got to be a way of fixing whatever got broken by installing VS11. Preferrably, I would like to keep VS11/.NET 4.5 installed, and not have to reinstall VS10 from scratch... However, I already tried "repairing" VS10 and it did not help. A: To put this isse to rest, I did have to uninstall VS11, and .NET 4.5. I also had to re-install .NET 4.0, as it seemed to have been corrupted in the process. This wasn't a "production" machine, btw, but it sure would have been nice to separate concerns. .NET 4.5 and VS11 installation should not have - in principle - destroyed a working .NET 4.0/VS2010 combination.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573518", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to check if mysql_query returned anything or not Possible Duplicate: mysql_fetch_array() expects parameter 1 to be resource, boolean given in select So I am trying to check if the following query returns any result or not $numUsersSameRatingQuery="SELECT * `user ratings` WHERE category='$category' AND categoryId='$categoryId' AND `userAromaRating`>0 "; $result=mysql_query($numUsersSameRatingQuery); $numResults=mysql_num_rows($result); if($numResults==0) { // do the INSERT INTO } else { //do the UPDATE SET } However, the above returns the following error and the if($numResults) is executed anyway each time. In other words, I can never get the else block to run. Here is the error Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\boozeDb\profileThis.php on line 141 Helps are appreciated. A: You could use is_resource to make sure that it's a resource. You could alternatively use an if statement to make sure that FALSE wasn't returned. To display the error, use mysql_error. Example: <?php // From http://ca2.php.net/manual/en/function.mysql-query.php $result = mysql_query('SELECT * WHERE 1=1'); if (!$result) { trigger_error('Invalid query: ' . mysql_error()); } A: mysql_query() either returns a statement handle (query succeeded) or a boolean FALSE (query failed). Your code does not check for error conditions and blindly assumes success. Modify the code to look like this: $result=mysql_query($numUsersSameRatingQuery) or trigger_error(mysql_error()); ^^^^^^^^^^^^^^^^^^^^^^--- add this Given your sample query, you're missing the FROM keyword, and should probably be: SELECT * FROM `user ratings` ^^^^^^ I would STRONGLY urge you to NOT use fieldnames that contain spaces. They're nothing but trouble. A: Just like everyone else has commented, an if statement or an "or die()" could help not generating that error again, while the error probably comes from the missing "FROM" in your query. I just felt the need to comment the fact that you're now making TWO queries to prevent some or all columns in the table from being duplicates: a SELECT and an INSERT. This could be done in ONE query and would speed up your code: INSERT ..(what you want to insert).. ON DUPLICATE KEY UPDATE ..(what to update if it already exists).. for more info here's MySQLs manual page about it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573519", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: datepicker in jade template I'm new to Jade and express and need to add datepicker from jquery UI to one of my layered popup.I have tried inline script and header javascript with onload without any luck. script(src='/javascripts/jquery-1.4.4.js') script(src='/javascripts/jquery-ui.js') script(type='text/javascript') function initDate() { $('#mdate').datepicker({dateFormat: 'yyyy-mm-dd'}); } input(type='text', name='mdate', id='mdate') Any suggestions or help would be appreciated. Thanks A: Try this code instead script(src='/javascripts/jquery-1.4.4.js') script(src='/javascripts/jquery-ui.js') script(type='text/javascript') $(function(){ function initDate() { $('#mdate').datepicker({dateFormat: 'yyyy-mm-dd'}); } }); input(type='text', name='mdate', id='mdate') All I'm doing is telling the page to wait till it's ready before applying the datepicker
{ "language": "en", "url": "https://stackoverflow.com/questions/7573521", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Execute a function on the first element matching selection using jQuery I know $('.test').each(testFunction); invokes the testFunction for all matching .test elements on the page. How do I tell it to do just the first matching one. I tried $('.test:first').each(testFunction); and it still seems to run for all of them. A: :first should work as you expected http://jsfiddle.net/guard/r5nUZ/ A: try $(".test").first(); this should select just the first element from that list. also if you are only trying to run it on one element why are you using each? just do testFuntion($(".test").first()); A: I think you should be able to use the .first() function in place of .each(). Looking at the documentation http://api.jquery.com/category/traversing/, that appears to be the function of choice. A: (function($) { $.fn.testFuntion = function() { return each( function() { console.log(this); }); } })( jQuery ); //$('.test:first').testFuntion(); or $('.test').each(function(i) { if ( i == 0 ) { testFuntion(); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7573523", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I pass the multi-line output of a function to a grep? I'm new to UNIX and having trouble with what is probably a very simple concept. I would like to take the output of an awk designed to return a single column of data (in this case, it's a couple of lines containing FC WWNs) and use that as a search parameter in a grep the same way I would use a file containing the column. My first thought was to simply type grep -f awk {'print $3'} myfile myotherfile Clearly, that didn't work. I know I could do this simply with two commands and an intermediate file (outputting my awk with a > to a new file, and the using the grep -f with it), but I would like to know if there's a way to do this without adding files. Background: I'm using AIX 5.3 and bash A: You can use the nifty $< bash idiom of bash to replace a file name argument with the output of a specified command. fgrep -f <(awk '{print $3}' myfile) myotherfile A: A common idiom that appears to work with GNU grep (don't know about AIX grep) is to use - as a specification for stdin. So in your case, if I've interpreted the commanded correctly, you'd use: awk {'print $3'} myfile | grep -f - myotherfile
{ "language": "en", "url": "https://stackoverflow.com/questions/7573525", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: self join in a table CustID Name ReferredBy 1 Neeta Sayam 2 Dolly Dilly 1 3 Meena Kimi 2 Find the names of all customers who are referred by others. the output should be dolly dilly and meena kimi. I have succesfully found out for customers who have reffred others by query SELECT c1.name FROM Customer c1 JOIN Customer c2 ON c1.custid=c2. ReferredBy A: Unless I'm missing something: SELECT * FROM Customer WHERE ReferredBy IS NOT NULL A: There are a lot of ways to achieve what you want, but one interesting is using CTE because it allows you to get reference by level, for example in your case level zero will be Neeta syam that has no reference, level one is dolly dilly and meena kimi. The following query will return dolly dilly and meena kimi which are in the level one specified by where reference = 1 like so: WITH CTEs (Id, CustomerName, Reference, RefCustomer) AS ( SELECT Id, Name, 0 As Reference, CONVERT(VARCHAR(length), 'No Reference') AS RefCustomer FROM Customers WHERE ReferredBy IS NULL UNION ALL SELECT c.CustId, c.Name, cs.Reference + 1, cs.CustomerName FROM Customers c INNER JOIN Ctes cs ON c.ReferedBy = cs.Id ) SELECT CustomerName, RefCustomer FROM Ctes WHERE Reference = 1;
{ "language": "en", "url": "https://stackoverflow.com/questions/7573526", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: left outer join with a where in sql query i have a sql query like this: select something from ( inner query here - outputs is correct: eg 2000 datasets ) as a left outer join tableA on tableA.id=innerQuery.id where someYear = -----------> had to change this "and" to "where" ( select max(tableYear) from tableC where etc.... ) eg years: 2011, 1999, 1901 max is 2011. 1978, 1981,1990 max is 1990. etc.. the problem i am having is, with the "where" statement, i am only getting fewer 1600 datasets; however if i were to key in a value and use "and", outputs comes out correct 2000. is there a way to use "where" with a left outer join and get all my outputs? A: If you test a column from a LEFT JOINed table in the WHERE clause, you force that join to behave as if it were an INNER JOIN. The correct method is to make that test part of the join condition. A: In a LEFT JOIN, it makes a difference whether you put the filter into the JOIN clause or into the WHERE clause. I explained the difference very detailed here: What is the difference in these two queries as getting two different result set? To summarize it in one sentence: if you want the full 2000 rows and not just 1600, you have to put the filter in the JOIN clause. A: Why not leave the condition as part of the join (as you have posted? somedate must be from the right table i.e. tableA and so it may be null. So if you want to get all the results, you have to account for that e.g. IsNull(somedate, '1/1/2000') = '1/1/2000' or (somedate = '1/1/2000' OR somedate is null)
{ "language": "en", "url": "https://stackoverflow.com/questions/7573527", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Data binding - Visual Studio 2010 I am working with Visual Studio 2010. Scenario: I have 2 comboboxes. Contents of first combobox: PC DB... Contents of Second combobox: Password reset Hardware problem SQL My question: When I select 'PC' in the first combo box I want 'Password Reset' and 'Hardware Problem' to show up. When I select 'DB' in first combobox I want 'SQL' to show up in the second combo box. Does anyone know how I can bind data from one combo box to the other ? Also when I click on 'DB' ->'SQL' then a 3rd list box with data under these two combo items should be populated. I feel this relates to data binding but not sure how to go about it. ANy idea or link I could refer to?? Please help. Thank you. A: this question is very broad. Basically you have nothing besides the problem. So it's hard for anyone to give you good advise because it would amount to quite a few lines of code. So I try to give you a high-level overview. The easiest way (without any desing-patterns or some advanced stuff) is just to put all you choices hardwired in combobox1. Then listen for the selecteditem-change event and fill combobox2 acording to what was selected. Rinse/Repeat with your optional combobox3. To move on you can pull the values out of database-tables or config files instead of hardwiring them. And finally you could move on to MVVM or a similiar pattern to to the theselction in a viewmodel and the representation in a view. For now think about the first one and try to implement it - should be quite easy.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573528", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# converting .xls to .csv without Excel Need to convert a .xls or .xlsx to a .csv without the use of Excel in an C#/ASP.net web app. The application is currently using the NPOI.dll for some functionality but I do not see any info on the codeplex wiki for NPOI for that particular functionality. Does anyone have any suggestions? Thanks A: There are libraries ( Excel Data Reader, for eg) that let you read excel. Once you are able to read data, writing to csv should be simple. A: ADODB.NET can be used to treat the Excel files as datasource. //string ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0;"; string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0;"; ConnectionString = string.Format(ConnectionString, @"FullPathToExcelFile"); OleDbConnection conn = new OleDbConnection(ConnectionString); conn.Open(); OleDbCommand cmdSelect = new OleDbCommand("SELECT * FROM [Sheet1$]", conn); OleDbDataAdapter oleDBAdapter = new OleDbDataAdapter(); oleDBAdapter.SelectCommand = cmdSelect; DataSet myDataset = new DataSet(); oleDBAdapter.Fill(myDataset); conn.Close(); // Do whatever with data in myDataset including export to csv... A: Have a look at the FileHelpers library. It will do exactly what you want. With FileHelpers, you can read from Excel files and write to csv or flat text files. And it's object oriented! All you have to do is to annotate classes with some attributes so that they match the source excel file. Consider this example: [DelimitedRecord("|")] public class CustomersVerticalBar { public string CustomerID; public string CompanyName; ... } Read using this: ExcelStorage provider = new ExcelStorage(typeof(CustomersVerticalBar)); provider.StartRow = 3; provider.StartColumn = 2; provider.FileName = "Customers.xls"; CustomerVerticalBar[] res = (CustomerVerticalBar[]) provider.ExtractRecords(); Example taken from here: http://filehelpers.sourceforge.net/example_exceldatalink.html A: .xls is a proprietary binary format which cannot be read in plain text format, so you will need office or Libre Office or something to read that... .xlsx is an xml based format, and should be possible just by parsing through the DOM... but you would still be manually iterating through each value and manually delimiting, etc. Have you considered using an xslt?
{ "language": "en", "url": "https://stackoverflow.com/questions/7573529", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: llvm Attribute::NoUnwind i'm running inside http://llvm.org/demo the following snippet: class X { public: ~X() __attribute((nothrow)); }; void a(X* p); void nothr() throw(); void b() { try { X x; a(&x); } catch (X* foo) { nothr(); } } I see that some of the calls, (for instance, to func_llvm_eh_typeid_for) have the Attribute::NoUnwind set: CallInst* int32_71 = CallInst::Create(func_llvm_eh_typeid_for, const_ptr_43, "", label_49); int32_71->setCallingConv(CallingConv::C); int32_71->setTailCall(false); AttrListPtr int32_71_PAL; { SmallVector<AttributeWithIndex, 4> Attrs; AttributeWithIndex PAWI; PAWI.Index = 4294967295U; PAWI.Attrs = 0 | Attribute::NoUnwind; Attrs.push_back(PAWI); int32_71_PAL = AttrListPtr::get(Attrs.begin(), Attrs.end()); } int32_71->setAttributes(int32_71_PAL); Since this calls are created with CallInst rather than InvokeInst, i presume the call themselves cannot throw, so it makes me wonder whats the purpose of the Unwind attribute in this context? A: It means that you don't have to worry about generating exception handling code or optimizing as if an exception could propagate through that section of code since you've already said it doesn't. If one happens to come through there then it should propagate correctly through to the next stack frame in your program.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573535", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: javascript resize with mouse I'd like to let my users resize a div from the 4 corners or the 4 sides with the mouse. I whish to use just Javascript, no JQ library please... A tiny little resize image in the right bottom corner would be a plus! Thanks A: Use CSS3 resize: both;, as seen here: http://dhtmlexamples.com/2011/01/20/creating-a-user-resizable-div-tag-using-css3/ <style type="text/css"> .isResizable { background: rgba(255, 0, 0, 0.2); font-size: 2em; border: 1px solid black; overflow: hidden; resize: both; width: 160px; height: 120px; min-width: 120px; min-height: 90px; max-width: 400px; max-height: 300px; } </style> <div class="isResizable">The quick brown fox jumps over the lazy dog.</div>
{ "language": "en", "url": "https://stackoverflow.com/questions/7573536", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is the best/easiest method of creating a site from mysql tables and PHP? I am new to PHP and this will be my first site using PHP and MySQL... please help me with my issue. Basically, I am beginning to create a site from scratch where there are 10 states and 8 regions in each state. I need to make pages for each state (10 pages) and pages for each region (80 pages). Furthermore, the pages cannot be named: example.com/state.php?state=New%20York There are specific filenames (slugs) in the states table and also the regions table. The urls will end up looking like this: example.com/new-york-something.php As far as the regions for each state, they will be placed into "state directories" which will be the same as the state filename. example.com/new-york-something/bronx-ny-something.php I get how to make the information show up on each page, the only part I need direction with is how to decipher what type of page it is based on the url or another way to have the pages generated. What is the most basic, simple method of doing this? I am not asking for anyone to do this for me, I am looking for guidance so I can efficiently learn and do this on my own. Your help is greatly appreciated. A: Honestly this is quite a large question, but i will try my best to hit a few key points. About the "slugs", easiest method would be using Apache's mod-rewrite for url-rewriting Working with mod-rewrite URLs such as "mysite.com/state/NY" or "mysite.com/state/NY/Bronx" would be parsed as urls like this : http://mysite.com/state.php?state=NY&region=Bronx This allows you to use a single PHP file that is being redirected to from different URLs by mod-rewrite, and hence dealing with all the data-fetching and processing on a single PHP file. This is done using .htaccess usually, you can read more about using .htaccess and mod-rewrite on google or this link: http://corz.org/serv/tricks/htaccess2.php Good luck! Shai. A: You will want to get familiar with mod_rewrite. It is an Apache module that will help you transform urls like this: example.com/newyork/bronx into: example.com/page.php?state=newyork&region=bronx Page.php will then load, parse the url variables, and generate the correct page for your visitors, all while keeping the url friendly. A great introduction to mod_rewrite can be found at http://www.workingwith.me.uk/articles/scripting/mod_rewrite, or just by googling mod_rewrite. A: You want to use something like mod_rewrite to rewrite the incoming URL from http://example.com/foo/bar to something like http://example.com/script.php?var1=foo&var2=bar. From there you can write the script to pull from the database and display output as appropriate.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573540", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Code completion C/C++ on Aptana doesn't work I'm using aptana studio 3 with C code and when I'm writting an acces to an structure it suggests in each position what variables I can use, but for simple variables it doesn't suggests anything without press control+space. Any idea how to change that? A: Aptana Studio doesn't include code completion for C/C++ by default. I would suggest you'll need to contact the plugin authors for C/C++ with that question.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573541", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Facebook Login w/ Java Web I'm trying to implement a Facebook login for my site and am having a world of trouble. I understand the difference between the client (JavaScript SDK) and server-side implementations, but am confused as to which is the correct approach. What I need is to store the user's info in my database (userID, email, name, etc.), so I know I'll need the data on the server side. I don't want to log in via the JS SDK and send the data to the back end because it can easily be spoofed, so here's what I tried: I've tried using the SDK and, once the user is logged in, refreshing the page to check for the cookie that Facebook puts in the session, but it doesn't seem to be present; the only cookie that's there is the session id. Additionally, I tried doing a server-side implementation, but this caused the Facebook log in screen to be in the main browser window instead of a popup. This is undesirable because it takes the user away from my site. To force the login workflow to be in a separate window, I've thought about popping up a child window that points to my login url that ultimately redirects to Facebook, but then I don't know when the user is done logging in (I'd need to refresh the main page to hide the facebook login button, etc.). Any help or ideas would be greatly appreciated! I'd like to do this the right way... not the easy way! A: Bottom line: use spring-social in java applications for connection to the social networks. It's cake! A: There is no official Facebook API for standard Java that I am aware of. Specifically for Facebook, your java app can use the REST API here http://restfb.com/
{ "language": "en", "url": "https://stackoverflow.com/questions/7573554", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: HtmlUnit, how to post form without clicking submit button? I know that in HtmlUnit i can fireEvent submit on form and it will be posted. But what If I disabled javascript and would like to post a form using some built in function? I've checked the javadoc and haven't found any way to do this. It is strange that there is no such function in HtmlForm... I read the javadoc and tutorial on htmlunit page and I Know that i can use getInputByName() and click it. BuT sometimes there are forms that don't have submit type button or even there is such button but without name attribute. I am asking for help in such situation, this is why i am using fireEvent but it does not always work. A: WebRequest requestSettings = new WebRequest(new URL("http://localhost:8080/TestBox"), HttpMethod.POST); // Then we set the request parameters requestSettings.setRequestParameters(Collections.singletonList(new NameValuePair(InopticsNfcBoxPage.MESSAGE, Utils.marshalXml(inoptics, "UTF-8")))); // Finally, we can get the page HtmlPage page = webClient.getPage(requestSettings); A: You can use a 'temporary' submit button: WebClient client = new WebClient(); HtmlPage page = client.getPage("http://stackoverflow.com"); // create a submit button - it doesn't work with 'input' HtmlElement button = page.createElement("button"); button.setAttribute("type", "submit"); // append the button to the form HtmlElement form = ...; form.appendChild(button); // submit the form page = button.click(); A: final HtmlSubmitInput button = form.getInputByName("submitbutton"); final HtmlPage page2 = button.click() From the htmlunit doc @Test public void submittingForm() throws Exception { final WebClient webClient = new WebClient(); // Get the first page final HtmlPage page1 = webClient.getPage("http://some_url"); // Get the form that we are dealing with and within that form, // find the submit button and the field that we want to change. final HtmlForm form = page1.getFormByName("myform"); final HtmlSubmitInput button = form.getInputByName("submitbutton"); final HtmlTextInput textField = form.getInputByName("userid"); // Change the value of the text field textField.setValueAttribute("root"); // Now submit the form by clicking the button and get back the second page. final HtmlPage page2 = button.click(); webClient.closeAllWindows(); } A: How about getting use of built-in javascript support? Just fire submit event on that form: HtmlForm form = page.getForms().get(0); form.fireEvent(Event.TYPE_SUBMIT); The code supposes you want to submit first form on the site. And if the submit forwards you to another site, just link the response to the page variable: HtmlForm form = page.getForms().get(0); page = (HtmlPage) form.fireEvent(Event.TYPE_SUBMIT).getNewPage(); A: Although this question has good and working answers none of them seems to emulate the acutal user behaviour quite well. Think about it: What does a human do when there's no button to click? Simple, you hit enter (return). And that's just how it works in HtmlUnit: // assuming page holds your current HtmlPage HtmlForm form = page.getFormByName("yourFormName"); HtmlTextInput input = form.getInputByName("yourTextInputName"); // type something in input.type("here goes the input"); // now hit enter and get the new page page = (HtmlPage) input.type('\n'); Note that input.type("\n"); is not the same as input.type('\n');! This works when you have disabled javascript exection and when there's no submit button available. IMHO you should first think of how you want to submit the form. What scenario is it that you want to test? A user hitting return might be a different case that clicking some button (that might have some onClick). And submitting the form via JavaScript might be another test case. When you figured that out pick the appropriate way of submitting your form from the other answers (and this one of course).
{ "language": "en", "url": "https://stackoverflow.com/questions/7573558", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: What is the computational model of ICON and SNOBOL I try to found computation model of programming languages like Icon and Snobol but i can't found the information about these programming languages...! I want know What the computational model of ICON and SNOBOL is? A: Snobol is functional and logic model (see the right side of this page http://en.wikipedia.org/wiki/SNOBOL) and Icon support Imperative model.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Open A New Layout, Then Return to the Previous I have my main.xml layout. From here, the user fills in information, and is to click a button that should bring them to another describe.xml layout. The question is: how do I get it so that you can press a button on main.xml to open up describe.xml, then when you hit a button on the describe.xml, you return to main.xml without any information previously inputted into main.xml lost? Thank you in advanced. A: There are three ways to do this 1) When you start Activity describe Activity don't finish() main Activity so that when you finish describe Activity main Activity will be resume without and lost of data 2) If you want to get data from describe Activity to main Activity you can start describe Activity by calling startActivityForResult and you can get result from describe Activity to main Activity 3) You can also save data to preference file A: Just store your information in a SharedPreference or a file or some static field in the override onPaused() method, and read out and fill information in the onResume() method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573563", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iPhone browser: Checking if iPhone app is installed from browser I have web page where I have Button that either opens app (if it installed) or directs to App store if app isn't installed. It all works if App is installed (I call into "MYAPP://"). However, if app is not installed Safari shows error message "Can not open URL" and that's it. Is there way to disable that message from JScript or is there another way to find out from JScript if app installed (instead of hitting app URL)? To MODERATOR: I saw someone asked similar question and Moderator wrongly marked it as duplicate. Please understand that question was specifically about doing it from Browser. Found somewhat suitable solution here BTW if someone interested in how to do same thing for Android, here is code. We are using Dojo library: dojo.io.iframe.send({ url: "yourApp://foo/bar", load: function(resp) { // nothing to do since it will automagically open App }, error: function () { window.location = "go to Android market"; } }); A: here is a code that works on iOs, even if the "Can not open URL" still show. window.location = "yourApp://foo/bar"; clickedAt = +new Date; setTimeout(function() { if (+new Date - clickedAt < 2000) { window.location = "go to Android market"; } }, 500); Thanks for the android solution. A: At Branch we use a form of the code below--note that the iframe works on more browsers. Simply substitute in your app's URI and your App Store link. By the way, using the iframe silences the error if they don't have the app installed. It's great! <!DOCTYPE html> <html> <body> <script type="text/javascript"> window.onload = function() { // Deep link to your app goes here document.getElementById("l").src = "my_app://"; setTimeout(function() { // Link to the App Store should go here -- only fires if deep link fails window.location = "https://itunes.apple.com/us/app/my.app/id123456789?ls=1&mt=8"; }, 500); }; </script> <iframe id="l" width="1" height="1" style="visibility:hidden"></iframe> </body> </html> If others have better solutions to detect whether the URI scheme call actually failed, please post! I haven't seen one, and I've spent a ton of time looking. All existing solutions just rely on the user still being on the page and the setTimeout firing. A: I've combined a few things and used the following code to check if it's an iOS device before using the try/catch method from chazbot. Unfortunately, the device still throws a pop-up box to the user saying the address is invalid...anyone know if this is expected behavior for trying to open an invalid URL within a "try" block? var i = 0, iOS = false, iDevice = ['iPad', 'iPhone', 'iPod']; for ( ; i < iDevice.length ; i++ ) { if( navigator.platform === iDevice[i] ){ iOS = true; break; } } try { //run code that normally breaks the script or throws error if (iOS) { window.location = "myApp://open";} } catch(e) { //do nothing } A: There are a few things you can do to improve on other answers. Since iOS 9, a link can be opened in a UIWebView or in a SFSafariViewController. You might want to handle them differently. The SFSafariViewController shares cookies across apps, and with the built in Safari. So in your app you can make a request through a SFSafariViewController that will set a cookie that says "my app was installed". For instance you open your website asking your server to set such cookie. Then anytime you get a request from a SFSafariViewController you can check for that cookie and redirect to MYAPP:// if you find it, or to the app store if you don't. No need to open a webpage and do a javascript redirection, you can do a 301 from your server. Apps like Messages or Safari share those cookies. The UIWebView is very tricky since it is totally sandboxed and shared no cookies with anything else. So you'll have to fallback to what has been described in other answers: window.onload = function() { var iframe = document.createElement("iframe"); var uri = 'MYAPP://'; var interval = setInterval(function() { // Link to the App Store should go here -- only fires if deep link fails window.location = "https://itunes.apple.com/us/app/my.app/id123456789?ls=1&mt=8"; }, 500); iframe.onload = function() { clearInterval(interval); iframe.parentNode.removeChild(iframe); window.location.href = uri; }; iframe.src = uri; iframe.setAttribute("style", "display:none;"); document.body.appendChild(iframe); }; I've found it annoying that this will prompt the user if they want to leave the current app (to go to your app) even when your app is not installed. (empirically that seems only true from a UIWebView, if you do that from the normal Safari for instance that wont happen) but that's all we got! You can differentiate the UIWebView from the SFSafariViewController from your server since they have different user agent header: the SFSafariViewController contains Safari while the UIWebView doesn't. For instance: Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Mobile/14E269 -> UIWebView Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E269 Safari/602.1 -> SFSafariViewController Other considerations: * *in the first approach, you might want to handle uninstalls: if the user uninstalls your app, you still have a cookie that says that the app is there but it's not, so you might end up with the "Can not open URL" message. I've handled it by removing the cookie after a few tries that didn't end up opening the app (which I know because at every app open I'm resetting this failed tries cookie) *In the second case, it's unclear if you're better off using a setInterval or setTimeout. The issue with the timeout is that if it triggers while a prompt is on, it will be ignored. For instance if you open the link from Messenger, the os will ask you "Leave Messenger? You're about to open another app" when the iframe tries to load your app. If you don't respond either way within the 500ms of the timeout, the redirection in the timeout will be ignored. *Finally even though the UIWebView is sandboxed, you can give it a cookie to identify it, pass it in your deeplink, and save this id as corresponding to device with your app in your server when your app opens. Next time, if you see such a cookie in the request coming from the UIWebView, you can check if it matches a known device with the app and redirect directly with a 301 as before. A: I think you can still use the app url as a test. Try wrapping it in a try...catch block, try { //run code that normally breaks the script or throws error } catch(e) { //do nothing }
{ "language": "en", "url": "https://stackoverflow.com/questions/7573566", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: Custom Splash Screen - Android Currently my android application shows a black screen with a loading wheel as it processes the user's request i:e as it gets content from the server. I would like to modify this screen to include an icon (image) that fades in and out continuously instead of the loading wheel. Is there any possible way to do it? A: Yes, you'll use an Alpha Animation See here and here and lastly here for a good tutorial on Animations with some nice code. In order to "chain" your animations so that one starts after the other you'll use an Animation listener and start the other one from the onAnimationEnd method callback. Don't forget to put an if statement in there that checks to see if your stuff is done loading otherwise you'll end up with infinite recursion of your fade in and fade out.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573568", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Is this email regex complete I'm following these specifications from wikipedia. [^\.]([a-zA-Z\d\!\#\$%&\'\*\+\-\/\=\?\^_`\{|\}\~]|[^\.][\.]{1})+[^\.]@[a-zA-Z\d\-\_]+(\.[a-z]{2,5}){1,2} How can it be improved/shortened? PS: I know there are multitudes of email validators already made, this is strictly for my own learning in regards to regex. Thanks. A: Domain names cannot contain underscores, so you should remove this from the part after the @. What about sub-domains? I don't think the given regex will match someone@subdomain.example.com Personally, I've always used /^[a-zA-Z0-9._%+-]+@([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,6}$/ which does not match the entire RFC-2822 specification, but does the job for >99.9% of real-world email addresses. A: If you want to learn about validating email addresses with regular expressions and some of the trade-offs, read this article http://www.regular-expressions.info/email.html Another good source are widely used open source libraries or applications that contain functions for validating email. Your regex indeed doesn't match emails with subdomains, which you can achieve by adding the dot to the 1st character class after the @ sign [^\.]([a-zA-Z\d\!\#\$%&\'\*\+\-\/\=\?\^_`\{|\}\~]|[^\.][\.]{1})+[^\.]@[a-zA-Z\d\-\_\.]+(\.[a-z]{2,5}){1,2}
{ "language": "en", "url": "https://stackoverflow.com/questions/7573580", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make website compatible with every browser I am trying to make new website and I would like to know how to make it compatible with cross-browser as now I am able to view my website perfectly with Google chrome and when I see the same with Firefox 7.0 it's looking very ugly and with IE 8 its looking better.So I would like to know how to make compatible. Any suggestions will be greatly appreciated! A: Every browser will render differently many things, mainly as they render differently some CSS properties (you can check different browser rendering here www.w3schools.com/cssref/). A commonly used solution is to differentiate the CSS stilesheets for every possible browsers. You can detect the client browser via javascript: http://www.w3schools.com/js/js_browser.asp and set different css again via javascript. A complete example here: http://rafael.adm.br/css_browser_selector/ A: Each specific incompatibility will require a different solution. As a general guideline use frameworks such as jQuery and avoid browser-specific code, then when you find an incompatibility ask about that specific issue. Also, you should not aim for pixel-by-pixel compatibility between browsers, CSS is not actually designed for that. A: One of the best ways is to use standardized code. Avoid using "HTML 5", because this still has a lot of browser specific implementations (as it is not yet a standard). HTML4 or XHTML1 should work on most browsers (Safari, Opera, Firefox, Chrome, IE7+), and show it more or less the same. As a web developer you should check with multiple browsers if your sites works ok. Using the ISO standards give you a good start: http://validator.w3.org/ Testing with a lot of browsers can be done using services like http://browsershots.org
{ "language": "en", "url": "https://stackoverflow.com/questions/7573581", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using one search form to search multiple models I am working a simple rails app and i would like to know how possible it is to use one search form to search inside multiple models. like i have a story model and a book model. this search form should be able to search the both models with a single parameter. <%= for_tag :url => search_path %> <%= text_field_tag :q %> <% end %> How can i make this search from work for multipple models A: Whatever search you need to do, is done inside an action in a controller. You could basically create a controller, say search_controller and have an action say, item def item if params[:q] @found_stories = Story.find_all_by_...(params[:q]) @found_books= Book.find_all_by_...(params[:q]) end end Then you could use the objects @found_stories and @found_books in your view to show the search results. This is just an example of how you could do to fulfill your requirement. Thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573587", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Variable number of function arguments Lua 5.1 In my Lua script I'm trying to create a function with a variable number of arguments. As far as I know it should work like below, but somehow I get an error with Lua 5.1 on the TI-NSpire (global arg is nil). What am I doing wrong? Thanks! function equation:init(...) self.equation = arg[1] self.answers = {} self.pipe = {arg[1]} self.selected = 1 -- Loop arguments to add answers. for i = 2, #arg do table.insert(self.answers, arg[i]) end end instance = equation({"x^2+8=12", -4, 4}) A: Luis's answer is right, if terser than a beginner to the language might hope for. I'll try to elaborate on it a bit, hopefully without creating additional confusion. Your question is in the context of Lua embedded in a specific model of TI calculator. So there will be details that differ from standalone Lua, but mostly those details will relate to what libraries and functions are made available in your environment. It is unusual (although since Lua is open source, possible) for embedded versions of Lua to differ significantly from the standalone Lua distributed by its authors. (The Lua Binaries is a repository of binaries for many platforms. Lua for Windows is a batteries-included complete distribution for Windows.) Your sample code has a confounding factor the detail that it needs to interface with a class system provided by the calculator framework. That detail mostly appears as an absence of connection between your equation object and the equation:init() function being called. Since there are techniques that can glue that up, it is just a distraction. Your question as I understand it boils down to a confusion about how variadic functions (functions with a variable number of arguments) are declared and implemented in Lua. From your comment on Luis's answer, you have been reading the online edition of Programming in Lua (aka PiL). You cited section 5.2. PiL is a good source for background on the language. Unfortunately, variadic functions are one of the features that has been in flux. The edition of the book on line is correct as of Lua version 5.0, but the TI calculator is probably running Lua 5.1.4. In Lua 5, a variadic function is declared with a parameter list that ends with the symbol ... which stands for the rest of the arguments. In Lua 5.0, the call was implemented with a "magic" local variable named arg which contained a table containing the arguments matching the .... This required that every variadic function create a table when called, which is a source of unnecessary overhead and pressure on the garbage collector. So in Lua 5.1, the implementation was changed: the ... can be used directly in the called function as an alias to the matching arguments, but no table is actually created. Instead, if the count of arguments is needed, you write select("#",...), and if the value of the nth argument is desired you write select(n,...). A confounding factor in your example comes back to the class system. You want to declare the function equation:init(...). Since this declaration uses the colon syntax, it is equivalent to writing equation.init(self,...). So, when called eventually via the class framework's use of the __call metamethod, the real first argument is named self and the zero or more actual arguments will match the .... As noted by Amr's comment below, the expression select(n,...) actually returns all the values from the nth argument on, which is particularly useful in this case for constructing self.answers, but also leads to a possible bug in the initialization of self.pipe. Here is my revised approximation of what you are trying to achieve in your definition of equation:init(), but do note that I don't have one of the TI calculators at hand and this is untested: function equation:init(...) self.equation = select(1, ...) self.pipe = { (select(1,...)) } self.selected = 1 self.answers = { select(2,...) } end In the revised version shown above I have written {(select(1,...))} to create a table containing exactly one element which is the first argument, and {select(2,...)} to create a table containing all the remaining arguments. While there is a limit to the number of values that can be inserted into a table in that way, that limit is related to the number of return values of a function or the number of parameters that can be passed to a function and so cannot be exceeded by the reference to .... Note that this might not be the case in general, and writing { unpack(t) } can result in not copying all of the array part of t. A slightly less efficient way to write the function would be to write a loop over the passed arguments, which is the version in my original answer. That would look like the following: function equation:init(...) self.equation = select(1, ...) self.pipe = {(select(1,...))} self.selected = 1 -- Loop arguments to add answers. local t = {} for i = 2, select("#",...) do t[#t+1] = select(i,...) end self.answers = t end A: Try function equation:init(...) local arg={...} --- original code here end
{ "language": "en", "url": "https://stackoverflow.com/questions/7573588", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "26" }
Q: Can a foreign key be NULL and/or duplicate? Please clarify two things for me: * *Can a Foreign key be NULL? *Can a Foreign key be duplicate? As fair as I know, NULL shouldn't be used in foreign keys, but in some application of mine I'm able to input NULL in both Oracle and SQL Server, and I don't know why. A: Short answer: Yes, it can be NULL or duplicate. I want to explain why a foreign key might need to be null or might need to be unique or not unique. First remember a Foreign key simply requires that the value in that field must exist first in a different table (the parent table). That is all an FK is by definition. Null by definition is not a value. Null means that we do not yet know what the value is. Let me give you a real life example. Suppose you have a database that stores sales proposals. Suppose further that each proposal only has one sales person assigned and one client. So your proposal table would have two foreign keys, one with the client ID and one with the sales rep ID. However, at the time the record is created, a sales rep is not always assigned (because no one is free to work on it yet), so the client ID is filled in but the sales rep ID might be null. In other words, usually you need the ability to have a null FK when you may not know its value at the time the data is entered, but you do know other values in the table that need to be entered. To allow nulls in an FK generally all you have to do is allow nulls on the field that has the FK. The null value is separate from the idea of it being an FK. Whether it is unique or not unique relates to whether the table has a one-one or a one-many relationship to the parent table. Now if you have a one-one relationship, it is possible that you could have the data all in one table, but if the table is getting too wide or if the data is on a different topic (the employee - insurance example @tbone gave for instance), then you want separate tables with a FK. You would then want to make this FK either also the PK (which guarantees uniqueness) or put a unique constraint on it. Most FKs are for a one to many relationship and that is what you get from a FK without adding a further constraint on the field. So you have an order table and the order details table for instance. If the customer orders ten items at one time, he has one order and ten order detail records that contain the same orderID as the FK. A: 1 - Yes, since at least SQL Server 2000. 2 - Yes, as long as it's not a UNIQUE constraint or linked to a unique index. A: Here's an example using Oracle syntax: First let's create a table COUNTRY CREATE TABLE TBL_COUNTRY ( COUNTRY_ID VARCHAR2 (50) NOT NULL ) ; ALTER TABLE TBL_COUNTRY ADD CONSTRAINT COUNTRY_PK PRIMARY KEY ( COUNTRY_ID ) ; Create the table PROVINCE CREATE TABLE TBL_PROVINCE( PROVINCE_ID VARCHAR2 (50) NOT NULL , COUNTRY_ID VARCHAR2 (50) ); ALTER TABLE TBL_PROVINCE ADD CONSTRAINT PROVINCE_PK PRIMARY KEY ( PROVINCE_ID ) ; ALTER TABLE TBL_PROVINCE ADD CONSTRAINT PROVINCE_COUNTRY_FK FOREIGN KEY ( COUNTRY_ID ) REFERENCES TBL_COUNTRY ( COUNTRY_ID ) ; This runs perfectly fine in Oracle. Notice the COUNTRY_ID foreign key in the second table doesn't have "NOT NULL". Now to insert a row into the PROVINCE table, it's sufficient to only specify the PROVINCE_ID. However, if you chose to specify a COUNTRY_ID as well, it must exist already in the COUNTRY table. A: Yes foreign key can be null as told above by senior programmers... I would add another scenario where Foreign key will required to be null.... suppose we have tables comments, Pictures and Videos in an application which allows comments on pictures and videos. In comments table we can have two Foreign Keys PicturesId, and VideosId along with the primary Key CommentId. So when you comment on a video only VideosId would be required and pictureId would be null... and if you comment on a picture only PictureId would be required and VideosId would be null... A: By default there are no constraints on the foreign key, foreign key can be null and duplicate. while creating a table / altering the table, if you add any constrain of uniqueness or not null then only it will not allow the null/ duplicate values. A: it depends on what role this foreign key plays in your relation. * *if this foreign key is also a key attribute in your relation, then it can't be NULL *if this foreign key is a normal attribute in your relation, then it can be NULL. A: Simply put, "Non-identifying" relationships between Entities is part of ER-Model and is available in Microsoft Visio when designing ER-Diagram. This is required to enforce cardinality between Entities of type " zero or more than zero", or "zero or one". Note this "zero" in cardinality instead of "one" in "one to many". Now, example of non-identifying relationship where cardinality may be "zero" (non-identifying) is when we say a record / object in one entity-A "may" or "may not" have a value as a reference to the record/s in another Entity-B. As, there is a possibility for one record of entity-A to identify itself to the records of other Entity-B, therefore there should be a column in Entity-B to have the identity-value of the record of Entity-B. This column may be "Null" if no record in Entity-A identifies the record/s (or, object/s) in Entity-B. In Object Oriented (real-world) Paradigm, there are situations when an object of Class-B does not necessarily depends (strongly coupled) on object of class-A for its existence, which means Class-B is loosely-coupled with Class-A such that Class-A may "Contain" (Containment) an object of Class-A, as opposed to the concept of object of Class-B must have (Composition) an object of Class-A, for its (object of class-B) creation. From SQL Query point of view, you can query all records in entity-B which are "not null" for foreign-key reserved for Entity-B. This will bring all records having certain corresponding value for rows in Entity-A alternatively all records with Null value will be the records which do not have any record in Entity-A in Entity-B. A: Can a Foreign key be NULL? Existing answers focused on single column scenario. If we consider multi column foreign key we have more options using MATCH [SIMPLE | PARTIAL | FULL] clause defined in SQL Standard: PostgreSQL-CREATE TABLE A value inserted into the referencing column(s) is matched against the values of the referenced table and referenced columns using the given match type. There are three match types: MATCH FULL, MATCH PARTIAL, and MATCH SIMPLE (which is the default). MATCH FULL will not allow one column of a multicolumn foreign key to be null unless all foreign key columns are null; if they are all null, the row is not required to have a match in the referenced table. MATCH SIMPLE allows any of the foreign key columns to be null; if any of them are null, the row is not required to have a match in the referenced table. MATCH PARTIAL is not yet implemented. (Of course, NOT NULL constraints can be applied to the referencing column(s) to prevent these cases from arising.) Example: CREATE TABLE A(a VARCHAR(10), b VARCHAR(10), d DATE , UNIQUE(a,b)); INSERT INTO A(a, b, d) VALUES (NULL, NULL, NOW()),('a', NULL, NOW()),(NULL, 'b', NOW()),('c', 'b', NOW()); CREATE TABLE B(id INT PRIMARY KEY, ref_a VARCHAR(10), ref_b VARCHAR(10)); -- MATCH SIMPLE - default behaviour nulls are allowed ALTER TABLE B ADD CONSTRAINT B_Fk FOREIGN KEY (ref_a, ref_b) REFERENCES A(a,b) MATCH SIMPLE; INSERT INTO B(id, ref_a, ref_b) VALUES (1, NULL, 'b'); -- (NULL/'x') 'x' value does not exists in A table, but insert is valid INSERT INTO B(id, ref_a, ref_b) VALUES (2, NULL, 'x'); ALTER TABLE B DROP CONSTRAINT IF EXISTS B_Fk; -- cleanup -- MATCH PARTIAL - not implemented ALTER TABLE B ADD CONSTRAINT B_Fk FOREIGN KEY (ref_a, ref_b) REFERENCES A(a,b) MATCH PARTIAL; -- ERROR: MATCH PARTIAL not yet implemented DELETE FROM B; ALTER TABLE B DROP CONSTRAINT IF EXISTS B_Fk; -- cleanup -- MATCH FULL nulls are not allowed ALTER TABLE B ADD CONSTRAINT B_Fk FOREIGN KEY (ref_a, ref_b) REFERENCES A(a,b) MATCH FULL; -- FK is defined, inserting NULL as part of FK INSERT INTO B(id, ref_a, ref_b) VALUES (1, NULL, 'b'); -- ERROR: MATCH FULL does not allow mixing of null and nonnull key values. -- FK is defined, inserting all NULLs - valid INSERT INTO B(id, ref_a, ref_b) VALUES (1, NULL, NULL); db<>fiddle demo A: I think foreign key of one table also primary key to some other table.So it won't allows nulls.So there is no question of having null value in foreign key. A: The idea of a foreign key is based on the concept of referencing a value that already exists in the main table. That is why it is called a foreign key in the other table. This concept is called referential integrity. If a foreign key is declared as a null field it will violate the the very logic of referential integrity. What will it refer to? It can only refer to something that is present in the main table. Hence, I think it would be wrong to declare a foreign key field as null. A: I think it is better to consider the possible cardinality we have in the tables. We can have possible minimum cardinality zero. When it is optional, the minimum participation of tuples from the related table could be zero, Now you face the necessity of foreign key values to be allowed null. But the answer is it all depends on the Business.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "437" }
Q: Why member can't sign in when migrate membership database from ASP.NET MVC3 to MVC4 I manually migrate data from ASP.NET membership database to new membership structure in ASP.NET MVC4. (table name has changed from aspnet_users to Users, aspnet_membership to Memberships, and so forth) But when try to sign in using ASP.NET MVC4 sign in dialog, it can't signed in. So I wonder that if default hash algorithm changed in MVC4 or not. Why member can't sign in? or How can I set the hash algorithm to Sha1? or How to migrate membership database to MVC4 correctly? A: Hash algorithm is not related to ASP.NET MVC binaries. It is highly likely that you misconfigured something. On solution explorer inside VS, click on your project and there should be an icon (with a world and hammer side by side [it is scary I know] I guess) just top of your solution as follows : Click on it to fire up the configuration manager. See if you can configure your membership data there. If not, it is sure that you misconfigured something. UPDATE : Please also be sure that you have configured the passwordFormat inside the web.config correctly. It should be same as your old one. If your passwordFormat has been set to Encrypted on your old app, then you should use the same machine key which you have used to create passwords before. A: MVC4DP using Universal providers. How about checking configuration or Databases.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573592", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: css div height expender i'm trying to put an textarea expander on a div and i can't find the right element to set , here explanation of what i'm trying to do : in the textarea input tags in the bottom corner there is expander for the user to set the size he wants hes textarea to be my question is , is there a way to put something like that on a div? i don't looking for javascript code , css or html would be great. A: Use CSS3 resize: both;, as seen here: http://dhtmlexamples.com/2011/01/20/creating-a-user-resizable-div-tag-using-css3/ <style type="text/css"> .isResizable { background: rgba(255, 0, 0, 0.2); font-size: 2em; border: 1px solid black; overflow: hidden; resize: both; width: 160px; height: 120px; min-width: 120px; min-height: 90px; max-width: 400px; max-height: 300px; } </style> <div class="isResizable">The quick brown fox jumps over the lazy dog.</div>
{ "language": "en", "url": "https://stackoverflow.com/questions/7573593", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery: Hide div with no ID How can I hide a div with no ID? I have an application which creates few stickies. Some of them have no ID and some of the do have. How can I hide the ones with no ID? The position is not always the same. This is what I get in the HTML where I want to hide the last one. Is it possible I can hide the one with no ID? Note that the rest which have ID's, is a number generated randomly. Thanks alot. A: Try this: $("div.sticky:not([id])").hide(); The main idea is to use :not([id]) selector with element selector. fiddle: http://jsfiddle.net/57uQ8/ A: http://sandbox.phpcode.eu/g/d2956/2 <script> $(function(){ $("div.sticky").each(function(b){ if (!$(this).attr('id')){ $(this).hide(); } }); }); </script> will probably do it, assuming you want to show ONLY divs with no IDS and divs with class sticky
{ "language": "en", "url": "https://stackoverflow.com/questions/7573595", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Add an excel column header to single header using c sharp I am attempting to add a couple of new columns to an excel file. I can add the column pretty easily, but I can't figure out how to add a column header to the excel file. How on earth do you add a column header to a newly added column? Here is how I add 3 new columns to a An excel worksheet. Range rng = (Range)wkSheet.get_Range("A1", Type.Missing); rng.EntireColumn.Insert(XlInsertShiftDirection.xlShiftToRight, XlInsertFormatOrigin.xlFormatFromRightOrBelow); Range rng2 = (Range)wkSheet.get_Range("A1", Type.Missing); rng2.EntireColumn.Insert(XlInsertShiftDirection.xlShiftToRight, XlInsertFormatOrigin.xlFormatFromRightOrBelow); Range rng3 = (Range)wkSheet.get_Range("A1", Type.Missing); rng3.EntireColumn.Insert(XlInsertShiftDirection.xlShiftToRight, XlInsertFormatOrigin.xlFormatFromRightOrBelow); wkSheet.SaveAs("C:\\Code\\UPMC\\ISD\\EADIS\\UPMC.ISD.EADIS.ACO.ACOBackLoad\\App_Data\\test", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); A: You can write to any cell like so (this just writes to the "header" as an example): // Type _ = Type.Missing; wkSheet.Range["A1", _].Value2 = "Heading 1"; wkSheet.Range["B1", _].Value2 = "Heading 2"; wkSheet.Range["C1", _].Value2 = "Heading 3";
{ "language": "en", "url": "https://stackoverflow.com/questions/7573596", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Change python source while running Is it possible to change python source file while running an application and have this changes reflected immediately in the application? Let say I have a foo.py file with a class Foo. In other module I'm calling functions on the Foo on user action. Now, I would like to change source of the Foo without restarting the application and on next user input see the results of the new code. Would that be possible? A: The following module can probably change whatever you need, not that it's a good idea to use, other than to muck around : ) Note that it will not change your source, which would probably be a disaster, especially if you make a coding error. The 'safer' option would be to play with byteplay http://wiki.python.org/moin/ByteplayDoc Ok, now let's play! Say we want to change the function, to print its arguments in reverse order. To do this, we will add a ROT_TWO opcode after the two arguments were loaded to the stack. See how simple it is: >>> from byteplay import * >>> from pprint import pprint >>> def f(a, b): ... print (a, b) ... >>> f(3, 5) (3, 5) >>> c = Code.from_code(f.func_code) >>> c.code[3:3] = [(ROT_TWO, None)] >>> f.func_code = c.to_code() >>> f(3, 5) (5, 3) >>> f(3, 5) (5, 3) If you are using a defined set of options but want to preserve the same function call, you can also do something like the following class Foo(object): def fn(self): pass def op1(self): print "HELLO" #etc >>> a = Foo() >>> a.fn() >>> a.fn = a.op1 >>> a.fn() HELLO A: Yes, but it ill advised — code which changes itself (although necessary in some cases) is notoriously hard to debug. You're looking for the reload method. The way that you would get it to work would be to modify the source file and then call reload on the module, then repeat. You do have the option of re-assigning and modifying the code within the application itself — something which does not risk race conditions and it will also allow for a more consistent and testable environment. For an example, I would recomment Ignacio Vazquez-Abrams's answer. Have you tried to see what you could manage by merely changing a state (an external config file, database entry, etc)
{ "language": "en", "url": "https://stackoverflow.com/questions/7573599", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "25" }
Q: Choosing the right MySQL connection for PHP There seem to be a lot of choices for MySQL connection from PHP. I guess they all offer different feature sets. I just want to run a simple query, and so I'm attracted to the simplicity of mysql_connect(). Is this OK or are there any considerations I'm missing Thhanks A: If you just want to run a simple query, there really is no difference. If you're working on something bigger, use mysqli or PDO instead so you can use it's features. Especially prepared statements is something you really want to use. I would just forget about the old mysql-library. Mysqli is not harder to use, but it's a big improvement. A: Use mysqli instead. It has the same simplicity and it is the improved version of mysql_connect See documentation here. A: Even if you are dealing with a single query or a very simple project, use PDO. It's how DB stuff it's done nowadays and will likely be done in the future. I think that learning the legacy libraries (mysql, mysqli) is not a good deal right now. The learning curve is quite the same, and with PDO you have a basis for doing anything you want (e.g. changing DBMS). And, even if you choose to use the legacy, DBMS-bound libraries, please don't use mysql, and do use prepared statements (both mysqli and PDO have them). Don't do stuff like: mysql_query("SELECT * FROM users WHERE username = '$username' AND password = '$password'");
{ "language": "en", "url": "https://stackoverflow.com/questions/7573603", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Passing arguments to ForeignKey class I am using stdimage to auto resize my images, I have something like that : class Image(models.Model): image = stdimage.StdImageField(upload_to="images/uploads/", size=(width, height)) class Nevermind(models.Model): w, h = 300, 150 image = models.ForeignKey(Image) class Nevermind2(models.Model): w, h = 100, 100 image = models.ForeignKey(Image) So I would like pass width and heigth as arguments to the Image class. Thanks A: I'm not sure exactly what your goal is, but you could try using model methods to define extra paramenters with the models. #model class Nevermind2(models.Model): image = models.ForeignKey(image) def size(self): w,h = 100,100 return w, h #example use >>> a = Nevermind2.objects.get(pk=1) >>> a.size() (100,100) >>> w,h = a.size() >>> w 100 >>> h 100
{ "language": "en", "url": "https://stackoverflow.com/questions/7573605", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to check if a string is an object's instance variable or not? I have one question about the variables of an object, I would like to know if I can check if a string is an object's instance variable or not? Below, an example to illustrate my issue : I have an object - MyObject.h : @interface MyObject : NSObject { //Variables id myVariable1; id myVariable2; } @property (nonatomic, retain) id myVariable1; @property (nonatomic, retain) id myVariable2; And I have also an array list: NSArray * myArray = [[NSArray alloc] initWithObjects:@"myVariable1",@"myVariable2",@"myVariable3",@"myVariable4",nil]; I would like to know if it's possible to determinate which strings in the array list aren't defined as variable in the object MyObject. => myVariable3 and myVariable4 for this case. I tried to use "isKindOfClass", "isMemberOfClass", "valueForKeyPath", "valueForKey" but without success... Let me know if you have some advices to resolve my problem :) A: Assuming the properties aren't using a custom setter name, you could do: MyObject *object = ...; for (NSString *name in myArray) { SEL getterName = NSSelectorFromString(name); if ([object respondsToSelector:getterName]) { NSLog(@"MyObject has a method named %@", getterName); } else { NSLog(@"MyObject does not have a method named %@", getterName); } } A: I would create an object to use for comparison using the NSClassFromString class. if ([myClass isKindOfClass:NSClassFromString(myClassString)] { // class matches string } else { // class doesn't match } A: It's easier to check if values in the array are properties of some object. As in your case the valueForKey: should have worked only if myInstance1 and myInstance2 are non-nil objects. You'd just need to implement - (id)valueForUndefinedKey: method to return nil and all would be fine and dandy. You can also try using object_getInstanceVariable method while iterating through an array and fetching each possible instance variable separately. I believe that undeclared instances should return NULL pointer (as opposed to nil instances that are declared but undefined).
{ "language": "en", "url": "https://stackoverflow.com/questions/7573607", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CSS Table Columns not lining up I have the following Table example here: http://jsfiddle.net/Lu9y3/ Which is based on the Telerik example here: http://demos.telerik.com/aspnet-mvc/Grid/Paging?theme=vista which is a UI component I am using in an app I am building. As you can see they use two separate tables to achieve the fixed header and scrollable content. BUT the headers and columns in both tables still line up correctly. Even if I REMOVE the style from the <col> in the Telerik examples using Web Inspector the columns will still line up... And they are NOT using jQuery to adjust the width. So how come they have their columns lining up and mine do not? How are they doing this? A: The reason you are having issues is because you are using two separate tables. Tables adjust column width to the longest unbroken content. The way Telerik does it, they have four columns and have set the widths explicitly in all but the third column. This allows the third column to expand and fill the remaining space. Using table-layout:fixed will help but it will make all your columns evenly spaced regardless of content. I recommend setting the width of each column, or better yet make a class for each width and reuse that on the appropriate columns. Lined up sample I don't use classes in my example but I think you get the idea. I used overflow:hidden on th and td to make sure that longer content doesn't display over the other cells of the table. I also think the visual effect of the table works better with fewer columns seven or eight columns might be a bit overkill, but that's my personal opinion. A: Using table-layout: fixed; makes the table line up ;) A: I'm using Google Chrome, and when I open up the editor (F12) to Telerik's site and change the settings, they start not lining up. I've done some research, and according to W3.org on <col>, it looks like there is no way to globally name a <col> that you can use in multiple talbes (sadly). Also, in Telerik's example, it appears that the <col> definitions specify a width in the tag itself (likely manually placed via some JS). I think this is the only way to do it other than setting specific CSS rules, but that may not work as well as a more dynamic solution. Best of luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/7573610", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to receive POST data in django I've been trying to integrate a payment gateway into my site in django. I'm having trouble getting the response data from the payment gateway. The payment gateway has sample docs for php which looks like this : $ErrorTx = isset($_POST['Error']) ? $_POST['Error'] : ''; //Error Number $ErrorResult = isset($_POST['ErrorText']) ? $_POST['ErrorText'] : ''; //Error message $payID = isset($_POST['paymentid']) ? $_POST['paymentid'] : ''; //Payment Id In the view for the url that the payment gateway is redirecting to after entering card details etc, I'm checking if it's a GET if request.method == "GET" and then passing the request to a function. When I debug the request, I can see an empty query dict. and if I try something like res = request.GET['paymentid'] I get an error that says there's no key called paymentid. Am I missing something obvious? I'm still pretty new to django, so I'm sure I'm doing something wrong. A: res = request.GET['paymentid'] will raise a KeyError if paymentid is not in the GET data. Your sample php code checks to see if paymentid is in the POST data, and sets $payID to '' otherwise: $payID = isset($_POST['paymentid']) ? $_POST['paymentid'] : '' The equivalent in python is to use the get() method with a default argument: payment_id = request.POST.get('payment_id', '') while debugging, this is what I see in the response.GET: <QueryDict: {}>, request.POST: <QueryDict: {}> It looks as if the problem is not accessing the POST data, but that there is no POST data. How are you are debugging? Are you using your browser, or is it the payment gateway accessing your page? It would be helpful if you shared your view. Once you are managing to submit some post data to your page, it shouldn't be too tricky to convert the sample php to python. A: You should have access to the POST dictionary on the request object. A: for class based views, try this: class YourApiView(generics.ListAPIView): """ API endpoint """ def post(self, request, *args, **kwargs): print("request data") print(request.data)
{ "language": "en", "url": "https://stackoverflow.com/questions/7573611", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "35" }
Q: Stopping increment at specific height I am animating images within a logo in a slot-machine type of animation. I need it to stop animating once it gets to the top of the image (and send a callback if possible). Currently, this is how I'm accomplishing the animation: window.setInterval(function() { $('#title-1 img').animate({bottom : '-=60px'}) }, 5000); Any ideas on how I would get it to stop, and to send the callback? A: var interval = window.setInterval(function() { $('#title-1 img').animate({bottom : '-=60px'}, function(){ if(`some stop point`) clearInterval(interval); } ); }, 5000); A: So I assume you have a sprite image containing multiple logos, you want them to slide each 5 seconds until you reach the last one, and then call the callback? var cnt = 6, $img = $('#title-1 img'), i = 0; function animate_logo(cb) { if (i < cnt) { $('#title-1 img').animate({bottom : '-=60px'}); i += 1; setTimeout(function () {animate_logo(cb)}, 5000); } else { cb(); } }(); A: I would not suggest using a setInterval when dealing with animations due to the way newer browsers are making changes to the way setInterval and setTimeout work when the tab is not the active tab. var $title1 = $("#title-1"); var $title1img = $title1.find('img'); function anim(){ if ($title1.height() < parseInt($title1img.css("bottom"))) { setTimeout(function(){ $title1img.animate({bottom : '-=60px'},anim); },5000); } } $title1img.animate({bottom : '-=60px'},anim); Edit: another reason not to use setInterval to fire off animations is due to the reqeustAnimationFrame that was implemented in 1.6 and removed in 1.6.3, which will more than likely be added back in 1.7. If you write code now that will be compatible later, that's less maintenance you will have to do later if you end up being required to upgrade. Here's a jsfiddle http://jsfiddle.net/czUnU/ Edit: function... function animColumn(title,img){ function anim(){ if (title.height() < parseInt(img.css("bottom")) { setTimeout(function(){ img.animate({bottom : '-=60px'},anim); },5000); } } img.animate({bottom : '-=60px'},anim); } animColumn($("#title-1"),$("#title-1 img")); animColumn($("#title-2"),$("#title-2 img")); animColumn($("#title-3"),$("#title-3 img")); http://jsfiddle.net/czUnU/1/
{ "language": "en", "url": "https://stackoverflow.com/questions/7573612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jquery click function not working jQuery is not working with the pop-up div. What happens is when i click on any of the Click Me text, the pop-up div is shown. Then i click on either one or two and nothing happens!? If i click on one, two should disappear and vice versa. Copy the code below and try for yourself. What's the solution? <html> <head> <style type="text/css"> .ratecontainer { display:block; float:left; height:40px; } .ratecontainer a { color:#FFFFFF; text-decoration:none; } .ratebutton1 { padding:5px; color:#FFFFFF; cursor:pointer; background-color:#59758d; } .ratebutton1:hover { background-color:#4a6f8e; } .ratebutton2 { padding:5px; color:#FFFFFF; cursor:pointer; background-color:#59758d; } .ratebutton2:hover { background-color:#4a6f8e; } #info { position:absolute; text-align:left; width:950px; height:auto; top:100px; left:50%; z-index:20; margin-left:-475px; border:1px solid #000000; background-color:#FFFFFF; display: none; } </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> </head> <body> <script type="text/javascript"> $(function() { $('.ratebutton1').click(function() { $('.ratebutton2').hide(); }); $('.ratebutton2').click(function() { $('.ratebutton1').hide(); }); $('.infobutton').click(function() { var id = $(this).attr('id'); var row = '#box'+id; $('#info').css('display','block'); var ninfo = $(row).html(); $('#info').html(ninfo); }); }); </script> <div id="info"></div> <div class="menucontainer"><a id="0" class='infobutton'>Click Me </a></div> <div style="display:none;" id="box0"> <div class="ratecontainer"> <form action=""> <a class="ratebutton1">One</a><a class="ratebutton2">two</a> </form> </div> </div> </body> </html> A: I created a stub fiddle for your code: http://jsfiddle.net/guard/P4KYL/ Edit it removing any php-related cruft (and manually put multiple items where necessary) Then post the edited version back and I'll check what's wrong with it. A: $('.ratebutton1').click(function() { $('.ratebutton2').hide(); }); Right here is one issue I believe. Your buttons are not named .ratebutton1 but rather ratebutton1. Take out the period and try it. Hope it helps
{ "language": "en", "url": "https://stackoverflow.com/questions/7573618", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: track software DOWNLOAD I have a simple question here. Let say you have a website on which you have a software with links to download and install it on your computer. Is it possible to find out who or how many people have DOWNLOAD the software on their computer with something like Google Analytics for example? If we cannot get that information with Google Analytics, please provide me the tools that I can use to get that information. Thank you A: The only way would be to include code in your installation program to "phone home" and let you know that the user not just downloaded, but actually installed your software. Of course, this kind of action, if anyone should implement it, should always ask for explicit consent from the user, because, if done silently, could rightfully be qualified as malware/spyware, in my opinion.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573619", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: General Runtime Error being displayed instead of stack trace sharepoint 2010 I am trying to add a GridView to the aspx page ,but when I add it I get the error I have enabled debugging on the web.config file , but still I get this below error. Since a day I have been trying to add the gridview to the page, it does'nt let me do it. However, I am able to add the same gridview to another aspx page. Not sure of whats going wrong. Can someone please let me know of how can I get the stack trace which will help me let me know the probl. A: Janet, you're going to need to disable custom errors as indicated in the error page you're seeing. Add <customErrors mode="Off" /> in the web.config for your site to see the full details of the error. A: What this means is that when you are NOT on the local machine, you will be viewing this type of error whenever a runtime error occurs. When you are viewing this in local machine's browser, you can get the real error page. But, If you want to see this on the browser not on local machine, you WILL have to change web.config customErrors mode="RemoteOnly" to customErrors mode="Off" (Note that mode is case sensitive here, i.e "off" is not same as "Off").
{ "language": "en", "url": "https://stackoverflow.com/questions/7573626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CSS or HTML help to set maximum width , height of a Image I have a block in a table, where profile pictures of the users shows. but to maintain design space, I have made the block size 200px in width and 300px in height. Now I set the below CSS style on the pictures of the users: .max{ max-width:200px; max-height:300px; } If there is a large picture (suppose 300x400 px), then it re-sizes to 200x300 px (well doing). But my problem is that if there is a small picture (suppose 100x150px), then also it re-sizes it to 200x300px. But I want to set maximum width and height. So in my situation I want to display the original size of the pictures if it is smaller then 200x300px . But if it is large picture, then it will re-size to 200x300px. any help plz (how I can do it ?)... --(internet explorer 8.0 tested) If it cannot do in css, html is there any option to do in JavaScript ?. Is there any good source available ? A: .max{ height: auto; max-width: 100%; } Specify td width to 200px and for the table - table-layout:fixed. That should solve your problem A: Max width and height are just that.. a max, so, it shouldn't be affecting the smaller images. I just made a text html page and the smaller images worked fine with the max height and width set. A: You can use: .max { max-width: expression(this.width > 200 ? 200: true); } A: don't know much about css but this should do it in jquery $('.images_class').each(function(){ height = $(this).height(); width = $(this).width(); if( height > 200 || width > 300) $(this).css('height','200px').css('width','300px'); }); A: ... you might have to resort to javascript, if I understand your question correctly something like this might do it: $(document).ready( function(){ $('img').each( function(){ if( ($(this).width() < 200) && ( $(this).height() < 300 ) ){ $(this).css({'width' : $(this).width() +'px', 'height' : $(this).height() + 'px' ) } }) }) ... this would involve jQuery, didn't have a chance to test either. A: What you are saying is extremely strange. It sounds like actually you are setting width and height rather than max-*. I suggest you create a simple fiddle and see if the problem remains. If yes, then post a URL and I can look into it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573628", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Toast didnt work I have android project v.2.1. and I have a code, in the code I have Toast, but it doesn't work. Why? public void click(){ TextView color = (TextView) findViewById(R.id.text); switch(i){ case 1: table.setBackgroundColor(Color.RED); color.setText("Красный"); break; case 2: table.setBackgroundColor(Color.rgb (255, 127, 0) ); color.setText("Оранжевый"); break; case 3: table.setBackgroundColor(Color.YELLOW); color.setText("Желтый"); break; case 4: table.setBackgroundColor(Color.GREEN) ; color.setText("Зеленый"); break; case 5: table.setBackgroundColor(Color.rgb (0,191,255) ); color.setText("Голубой"); break; case 6: table.setBackgroundColor(Color.BLUE ); color.setText("Синий"); break; case 7: table.setBackgroundColor(Color.rgb (160,32,240) ); color.setText("Фиолетовый"); break; case 8: // i=1; Toast.makeText(getApplicationContext(), "Вы прошли все цвета",Toast.LENGTH_SHORT).show(); //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< MY TOAST! break; } Toast not in an OnCreate. A: Your statement to create and show the Toast is correct. It is likely you are having a logic error are you absolutely positive that your switch statement is using case 8? It would be a good idea to put some log statements inside each case that print out which case it is so you can debug what is happening easier. Im not certain what the rest of your activity looks like but this appears to be some kind of click listener callback method. If that is the case you should not have TextView color = (TextView) findViewById(R.id.text); Inside a click callback. Doing so means that findViewById() is going to get called every time your view gets clicked. Since this is a relatively expensive method to call its more appropriate to call it once in your onCreate and just keep the reference that you get back for all other times you'll need it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573629", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to pass data from context menu to alert dialog in Android? The method below happens when an item in a ListActivity is long pressed. The idea is to delete that item from the database and for that I need to call mNotesAdapter.deleteNote(ID). Which works fine if I don't use an AlertDialog; but I should use one for delete confirmations. But I don't know how to pass the menu info, or the id itself to the onClick method. @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo)item.getMenuInfo(); switch (item.getItemId()) { case R.id.contextmenu_item_remove: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Are you sure you want to delete this note?"); builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { // VARIABLE menuInfo IS NOT ACCESSIBLE HERE, NOW WHAT? mNotesAdapter.deleteNote(menuInfo.id); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); builder.show(); return true; } return super.onContextItemSelected(item); } A: You should be able to access the reference if you mark it as final. To answer the other question in your comment, final doesn't mean the contents of the object can't be changed. It just means that the reference can't move to another object. When you enter that method, you're immediately creating a new reference to a new AdapterContextMenuInfo in the first line. Then you're creating a new OnClickListener that will only act on that one object that menuInfo is creating.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573630", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: android multi table adapters queries I've been reading about having multiples tables in a SQLite database in Android. One approach is to have 1 adapter class for each table, and each adapter will implement CRUDs methods for each table. My questions are: * *Is this the best aproach to handling differents tables in one SQLite database?. *In this case, how can I execute sql queries between tables?. A: Make various instances of SQLiteHelper sqLiteHelper1, sqLiteHelper2; sqLiteHelper1 = SQLiteHelper(context, MYDATABASE_NAME1, null,MYDATABASE_VERSION); sqLiteHelper2 = SQLiteHelper(context, MYDATABASE_NAME2, null,MYDATABASE_VERSION); sqLiteDatabase1 = sqLiteHelper1.getWritableDatabase(); sqLiteDatabase2 = sqLiteHelper2.getWritableDatabase(); using sqLiteDatabase1, sqLiteDatabase2, access the data of different tables.. I hope this works :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7573634", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Executor thread keeps running after hot deploy Is there any way to know when a war is being hot deployed so I can shutdown the old executor that is running scheduled tasks? I'm using jboss 6 and I have a scheduled thread pool that is updating data periodically in the background. When I hot deploy that thread pool is not shutdown and new starts up so I have multiple scheduled thread pools. Thanks for any input. A: Yes, but it depends on where you start your Executor and which technology you use: * *in ServletContextListener: start Executor in contextInitialized() and shut it down in contextDestroyed(). *in servlet, start Executor in init(), shut it down with destroy() *in EJB/Spring bean: start in method annotated with @PostConstruct, shutdown in @PreDestroy. A: Sure. It depends on how do you run this thread. If for example you are running it from sevlet use servlet's destroy() method to stop it. If you are using Spring use lifecicle of its Application context.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573639", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jquery spritefy pause and restart I'm useing this plugin: http://www.spritely.net/ Can anyone tell me why the variable $sprite doesn't re-execute? function animate_header() { var $sprite = $('#header') .sprite({ fps: 30, no_of_frames: 4, // the following are optional: new in version 0.6... start_at_frame: 1, rewind: false, on_last_frame: function(obj) { // you could stop the sprite here with, e.g. obj.spStop(); } }) .active(); } var init = setInterval("animate_header()", 1000); I also tried this: function animate_header() { $('#header') .sprite({ fps: 30, no_of_frames: 4, // the following are optional: new in version 0.6... start_at_frame: 1, rewind: false, on_last_frame: function(obj) { // you could stop the sprite here with, e.g. obj.spStop(); } }) .active(); } var init = setInterval("animate_header()", 1000); The function itself executes every second. But the sprite doesn't. A: This is what worked for me. I set the options first, then I looped it with the spStart function. $('#header') .sprite({ fps: 30, no_of_frames: 4, start_at_frame: 1, rewind: false, on_last_frame: function(obj) { // you could stop the sprite here with, e.g. obj.spStop(); } }); setInterval ( "$('#header').spStart()", 1000 ); A: For anyone else that might happen to stumble on this, use .destroy() The animation seems to break after running a few times every other way, but destroy fixes it :) A: try replacing .active(); with .spStart(); at the end of your code. Looks like obj.spStop() that is called on last frame just kills animation dead and it needs a jump start to get it going... Worked for me :) A: I ended up doing this. Wich worked as I wanted. function loop() { $('#bird').sprite({fps: 7, no_of_frames: 4, play_frames: 4}); var t = setTimeout(function(){ loop() }, 2000); } loop() Thanks for any replies though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573640", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Anchor property won't save on Windows Form I have an existing solution with various windows forms. I went through to make some cosmetic changes to controls on the forms (resize, anchoring buttons), but for some reason the changes I am making to the Anchor property of buttons do not get saved (Save button anchor is Top, Left and I am trying to change to Bottom). More specifics: If I make the change and run the application, the form will render correctly with the button anchored to the bottom of the form. I am using Team Foundation Server, and after a compare of server version and my version, the only difference I see is in the forms .resx file: <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base32"> Changed To <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> All other files for the form are identical. After I check in my code, close out and open up the solution again, the anchor is back to Top, Left I am working on Windows 7 64 bit, and the solution is 32 bit. Not sure if that has anything to do with it, as I have not been able to get another programmer on a 32 bit machine to try it out. Thanks in advance for any replies.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pointer arithmetic with shared memory I don't understand what exactly happens in the following lines: * *unsigned char *membershipChanged = (unsigned char *)sharedMemory; and *float *clusters = (float *)(sharedMemory + blockDim.x); I assume that in #1 sharedMemory is effectively renamed into membershipChanged, but why would you add the blockDim to the sharedMemorypointer. Where does this address point? sharedMemory was created with extern __shared__ char sharedMemory[]; The code I found in a CUDA kmeans implementation. void find_nearest_cluster(int numCoords, int numObjs, int numClusters, float *objects, // [numCoords][numObjs] float *deviceClusters, // [numCoords][numClusters] int *membership, // [numObjs] int *intermediates) { extern __shared__ char sharedMemory[]; // The type chosen for membershipChanged must be large enough to support // reductions! There are blockDim.x elements, one for each thread in the // block. unsigned char *membershipChanged = (unsigned char *)sharedMemory; float *clusters = (float *)(sharedMemory + blockDim.x); membershipChanged[threadIdx.x] = 0; // BEWARE: We can overrun our shared memory here if there are too many // clusters or too many coordinates! for (int i = threadIdx.x; i < numClusters; i += blockDim.x) { for (int j = 0; j < numCoords; j++) { clusters[numClusters * j + i] = deviceClusters[numClusters * j + i]; } } ..... A: sharedMemory + blockDim.x points blockDim.x bytes away from the base of the shared memory region. The reason you might do something like this is to suballocate in shared memory. The launch site of the kernel which includes find_nearest_cluster dynamically allocates some amount of shared storage for the kernel. The code implies that two logically different arrays reside in the shared storage pointed to by sharedMemory -- membershipChanged, and clusters. The pointer arithmetic is simply a means to get a pointer to the second array.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573654", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jquery dialog best approach My scenario is: 1. I have a link in my page that opens a dialog. 2. Inside this dialog may have another link that opens another dialog, and so on.. What is the best approach to resolve this problem? Where this dialogs will be created? -- I tried this: In my page I declare a div to be the placeholder of all my dialogs: <div id="dialog-placeholder"> </div> And in my javascript code done something like this: $(".bs-icon").live("click", function () { var dp = $("#dialog-placeholder"); dp.html("<div id='dialog'></div>"); //load index page in dialog $.get("/Car/IndexLookup", function (response) { dp.find("#dialog").html(response); var dialog = dp.find("#dialog").dialog({ modal: true, width: 700, height: 400, close: function (ev, ui) { $(this).remove(); } }); }); }); For now, only one dialog will have focus. This works, but it is a good way? A: You can define if you want your dialog to stack or not on other dialogs. So, you get to decide which dialog you see when multiple dialogs are called. (from the docs) dialog option: stack Specifies whether the dialog will stack on top of other dialogs. This will cause the dialog to move to the front of other dialogs when it gains focus. Code examples Initialize a dialog with the stack option specified. $( ".selector" ).dialog({ stack: false }); Get or set the stack option, after init. //getter var stack = $( ".selector" ).dialog( "option", "stack" ); //setter $( ".selector" ).dialog( "option", "stack", false );
{ "language": "en", "url": "https://stackoverflow.com/questions/7573657", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: C++ template help, using a template for integrations Hi i'm following a tutorial and video i found online , im trying to make a template to preform a numerical integration of a function where a user can decide which form of integration to preform, im trying to keep it to one file as not to use headers and not use massive ammounts of loops , the code for the first integration works fine on its own but when i run it through a template i get the wrong answer and the same value 1.9147e-307 for every input what am i doing wrong? #include <iostream> #include <cmath> #include <ctime> #include <cstdlib> #include<conio.h> using namespace std; //declared function double F(double X) { double f; f = (X*X); return f; }; double unifRand() { return rand() / double(RAND_MAX); }; template<typename T> class INTG{ private: T a; T b; T n; public: INTG(T a, T b,T n){ INTG::a = a; INTG::b = b; } ~INTG(){} T MC() { // some code return ans;} T SIMPC(){ // Simpson integration code here return a+b+n; } }; int main() { double a,b,mc,simp,ans; int OP,n; cout<<"Enter 1 for Monte Carlo Integration , Enter 2 for Composite Simpson Integration, enter 3 for trapezoidal int...."<<endl; cin>>OP; clock_t start = clock(); if (OP == 1) { cout<<"Enter lower limit of integration"<<endl; cin>>a; cout<<"Enter upper limit of integration"<<endl; cin>>b; cout<<"Enter number of iterations"<<endl; cin>>n; ans = INTG<double>::MC(a, b, n); INTG<double> MyCalc(a,b,n); cout<< ans <<endl; //mc = INTG::MC(a, b, n); getch(); } } A: ans is never assigned a value. That would account for your 1.9147e-307. Did you intend ans = MyCalc.MC(); before the cout ? Also INTG(T a, T b,T n){ INTG::a = a; INTG::b = b; } Is better described as INTG(T a, T b, T n):a(a),b(b),n(n) {} Initializing instead of assigning, and remembering n. So the calculation sequence would be INTG<double> MyCalc(a,b,n); ans = MyCalc.MC(); A: if (OP = 1) { ...should be... if (OP == 1) {
{ "language": "en", "url": "https://stackoverflow.com/questions/7573658", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Silverlight out of browser in SharePoint webpart I have an issue with my Silverlight webpart in a SharePoint 2010 site. The Silverlight app works great in the site and even out of browser. The issue I'm having is how to autoupdate the out of browser app. I currently have this: if (Application.Current.IsRunningOutOfBrowser) { App.Current.CheckAndDownloadUpdateCompleted += new CheckAndDownloadUpdateCompletedEventHandler(Current_CheckAndDownloadUpdateCompleted); App.Current.CheckAndDownloadUpdateAsync(); } void Current_CheckAndDownloadUpdateCompleted(object sender, CheckAndDownloadUpdateCompletedEventArgs e) { if (e.Error == null && e.UpdateAvailable) { MessageBox.Show("Application updated, please restart to apply changes."); } if (e.Error != null) { MessageBox.Show(e.Error.Message); } } but it doesn't run when it's SharePoint. I have to currently send out an email to all of my users thay may be using this app out of browser and have them uninstall and install it again. Does this have something to do with how SharePoint uses security? When a user double clicks on the desktop icon to open the oob app, it does give a credential login. My guess is that's what's throwing off the auto update. Thanks! A: The fix was to sign the xap files and place this code after authentication takes place!
{ "language": "en", "url": "https://stackoverflow.com/questions/7573663", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Include my own mb_string functions or use PHP's defaults? For a public app - do you think it's a good idea to assume the mb_string extension is enabled on all servers (or almost all, like 95%)? Are there hosts out there that disable this extension? A: I think most have it enabled by default but I've known a few hosting providers that don't, and who also then refused to enable it (never did get a good reason out of them). If you want all users to be able to install the app on their server without any changes then you'll probably want to roll your own set of functions. However it might be a better solution to make mb_string a pre-requisite of your app (and perhaps test for it's existence in the installation script) then you'd be able to save yourself that extra work, while still providing a satisfactory user experience. If you take Drupal as an example of a public app, they actually roll their own functions (e.g. drupal_substr() and drupal_strlen()), in which they test for the existence of the mb_string extension and make the decision on how to run the function based on that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573668", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Silverlight 4: how to show ToolTip on keyboard focus (revised) My original question: Is there an easy way for a ToolTip to be shown when an item gets keyboard focus, not just mouse over? We have a list of items with tooltips that users will probably tab through, and the desired behavior is for a tooltip to be shown then too. Added example XAML. A HyperlinkButton with the Tooltip set is what needs the keyboard focus as well. <DataTemplate x:Key="OfferingItemDT"> <HyperlinkButton Command="{Binding Path=NavigateToLinkCommand}" ToolTipService.ToolTip="{Binding Tooltip}"> <Grid x:Name="gOfferingButtonRoot" Width="275" MaxHeight="78" Margin="5,3"> <Grid.ColumnDefinitions> <ColumnDefinition Width="40"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <Image x:Name="imgServiceOfferingIcon" Grid.RowSpan="2" VerticalAlignment="Top" Source="{Binding Path=Image, Converter={StaticResource ByteArrayToImageConverter}}" Stretch="UniformToFill" Margin="2,10,0,0" MaxHeight="32" MaxWidth="32" /> <TextBlock x:Name="txbOfferingTitle" Grid.Column="1" Grid.Row="0" Text="{Binding Title}" TextWrapping="Wrap" Style="{StaticResource OfferingTileTitleText}"/> <TextBlock x:Name="txbOfferingDesc" Grid.Column="1" Grid.Row="1" Style="{StaticResource OfferingTileBodyText}" Text="{Binding BriefDescription}" /> </Grid> </HyperlinkButton> </DataTemplate> Updated: Based on info in WPF: Show and persist ToolTip for a Textbox based on the cursor as well as Anthony's comments, I tried this code in the GotFocus eventhandler: private void showTooltip(object sender, RoutedEventArgs e) { HyperlinkButton hb = new HyperlinkButton(); ToolTip ttip = new ToolTip(); hb = sender as HyperlinkButton; ttip = ToolTipService.GetToolTip(hb) as ToolTip; ttip.IsOpen = true; } This seems like it would work, but ttip is always null. Help? A: "Easy" is subjective term. Yes its easy. On the same UI element on which you attach the ToolTip you can hook the GotFocus and LostFocus event handler the will use ToolTipService.GetToolTip to acquire the tooltip and the set IsOpen to true and false respectively. A: The missing part is to define the tooltip in XAML so that we can access the Tooltip element. <HyperlinkButton MouseLeftButtonUp="showTooltip"> <ToolTipService.ToolTip> <ToolTip> <TextBlock Text="My tooltip text"/> </ToolTip> </ToolTipService.ToolTip> <!-- ... --> </HyperlinkButton> Code behind private void showTooltip(object sender, RoutedEventArgs e) { FrameworkElement frameworkElement = (FrameworkElement)sender; ToolTip tooltip = ToolTipService.GetToolTip(frameworkElement) as ToolTip; if (tooltip != null) { tooltip.IsOpen = true; frameworkElement.MouseLeave += new MouseEventHandler(frameworkElement_MouseLeave); } } static void frameworkElement_MouseLeave(object sender, MouseEventArgs e) { FrameworkElement frameworkElement = (FrameworkElement)sender; frameworkElement.MouseLeave -= new MouseEventHandler(frameworkElement_MouseLeave); ToolTip tooltip = ToolTipService.GetToolTip(frameworkElement) as ToolTip; if (tooltip != null) { tooltip.IsOpen = false; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7573670", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get list of network printers silverlight I want to get the list of network printers through silverlight. I have seen a few examples of using WMI, but they are not available in Silverlight, so, I was wondering if there are any alternatives to find network printers through silverlight or at least the installed printers... There is also a question posted here A: In Silverlight 5, you can use EnumPrinters Win32 API call through PInvoke. The code is pretty long, so I put together a sample that shows how to enumerate the printers on the machine. http://10rem.net/blog/2011/09/27/enumerating-printers-using-pinvoke-in-silverlight-5 With Silverlight 4, you're out of luck. A: Its my understanding that you cannot do this. You don't have the control over this, it is simply handed off for its built in support. This is the same reason why you can't specify a printer - it just doesn't allow this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573672", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Set progress bar value according to the unknown length of text file I currently have a program which reads from a text file and then writes to a database after each line it reads, the size of the text file is undetermined, some days the file could be more or less lines than other days. I already have a swing worker that executes my functions so my progress bar works but right now I just have setIndeterminate to true so the user knows something is being done just not the actual progress. Is there a way I can increment the progress bar after each line is read, but have it not reach 100 too early or too late, preferably without reading the the text file entirely before hand. Thanks, Beef. A: I'd use File.length() to determine the file size. Then keep track of the number of bytes read to determine the progress. A: If the file size is known before you are starting to read it you can read it line-by-line and count the percentage after every line: count the number of bytes in each line and devide it by the total number of bytes (i.e. file.length()). A: and wrap output to the GUI (in your case the Progress from the JProgressBar) to the invokeLater(), because you are pretty out of the EDT, more in Concurency in Swing A: To determine the file size is easy using java.io.File so the problem here is to get the size in bytes actually read for a simple progress bar two possibilities come to mind: * *Estimation: Assume 1 Character = 1 Byte (or 1 Character = 2 Byte if your file is UTF-16,...). The 1 Byte guess will have you underestimate your actual size read so you will have a jump of the bar at the end depending on how many multi byte characters are in your file. *Calculate: Recode the characters read to a byte array using the files character encoding and take the length of the encoded array. *Count: As proposed by Brendan in the comments below, use a CountingInputStream (in correct order after Buffering) to count the bytes actually read. Nr. 2. seems unneccessary overhead for this case to me so I think I'd stick to Nr. 1 or Nr. 3 A: You can have in your app something like this image :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7573680", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Replace spaces but not when between parentheses I guess I can do this with multiple regexs fairly easily, but I want to replace all the spaces in a string, but not when those spaces are between parentheses. For example: Here is a string (that I want to) replace spaces in. After the regex I want the string to be Hereisastring(that I want to)replacespacesin. Is there an easy way to do this with lookahead or lookbehing operators? I'm a little confused on how they work, and not real sure they would work in this situation. A: Try this: replace(/\s+(?=[^()]*(\(|$))/g, '') A quick explanation: \s+ # one or more white-space chars (?= # start positive look ahead [^()]* # zero or more chars other than '(' and ')' ( # start group 1 \( # a '(' | # OR $ # the end of input ) # end group 1 ) # end positive look ahead In plain English: it matches one or more white space chars if either a ( or the end-of-input can be seen ahead without encountering any parenthesis in between. An online Ideone demo: http://ideone.com/jaljw The above will not work if: * *there are nested parenthesis *parenthesis can be escaped
{ "language": "en", "url": "https://stackoverflow.com/questions/7573686", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: support multiple OS versions incrementally I'd like to support Android 2.1 devices, but also would like to enable users to move my app to the SD card if they have Android 2.2+ The attribute for that is android:installLocation="auto" How can I still support 2.1 while enable this attribute for 2.2+? EDIT: I've set it with build 2.1 and I get a compilation error and I cannot launch my app. The reason I don't want to increase the build target to 2.2 is because if I do that and the app gets installed on 2.1, a bunch of exceptions are thrown and it crashes. I want to make sure that the app works perfectly on 2.1. For an example of what I mean, please see NoSuchMethodError: String.isEmpty A: An exact solution for you is in Android Manual. A: It can be done, set your minimum API level to 7 and your target API level to 8, more details are in the Dev Guide.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573687", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Search algorithm - Java I am finding it a little bit difficult to get a search algorithm to work properly in Java. Basically, the program has an array initialized. The user is supposed to enter a number via the keyboard, and Java will them print out the all the indexes where this number is found. My main problem lies in the fact that I want create a method which currently looks as follows: public static int[] linsearch(int[] numbers, int key) { int[] indexvalues = null; int n = 0; for (int i = 0; i < numbers.length; i++) { if (numbers[i] == key) { indexvalues[n] = i; n++;} } return indexvalues; } The idea behind this is that given an array, and a number (in this case identified by "key"), the program will create a new array in which the indexes of where the number "key" is found in the original array will be saved. Currently I get this error message: java.lang.NullPointerException. I have tried different approaches to initializing this array, but none have been succesful so far. Thus, any help will be very appreciated! A: The main difficulty stems from the fact that you don't know the size of the output array ahead of time. On the other hand, growing a Java array as needed is doable, but unpleasant. There are several ways to fix this. If I were you, I'd use a collection to store the indices: public static Collection<Integer> linsearch(int[] numbers, int key) { ArrayList<Integer> indexvalues = new ArrayList<Integer>(); for (int i = 0; i < numbers.length; i++) { if (numbers[i] == key) { indexvalues.add(i); } } return indexvalues; } You'll need to modify the calling code accordingly. I leave this as an exercise for the reader.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573688", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Doctrine 2 ORM creates classes with hateful CamelCase I created yaml configuration for Doctrine. When I'm trying doctrine orm:generate-entities, it creates php files with getters and setters in camel case. So, is_public field transforms into setIsPublic and getIsPublic methods. It's owful. How can I get set_is_public and get_is_public? I can manually edit generated php files, but I don't know what will happen when I change the schema. A: You can choose a naming strategy that Doctrine will use to generate the items using: Using a naming strategy you can provide rules for automatically generating database identifiers, columns and tables names when the table/column name is not given. This feature helps reduce the verbosity of the mapping document, eliminating repetitive noise (eg: TABLE_). For your specific case, I think you're looking at something like: $namingStrategy = new \Doctrine\ORM\Mapping\UnderscoreNamingStrategy(CASE_LOWER); $configuration()->setNamingStrategy($namingStrategy); The linked topic goes on to show you how you can write your own custom naming strategy. If you're using Symfony, it's even easier (like most things are with Symfony, but that's just my opinion) via config.yml: doctrine: orm: naming_strategy: doctrine.orm.naming_strategy.underscore A: Symfony's coding standards encourage Symfony users to use camelCase: Naming Conventions Use camelCase, not underscores, for variable, function and method names, arguments A: Personal advice - do not generate entities by doctrine orm:generate-entities. Use plain PHP to create class. Why? Orm uses reflection on privates to communicate with database. You dont need to generate setters and getters. I recomend You to use design patterns such as factory or constructor to achive Your goal. Decorators also should work fine. <?php class MyClass { private $id; private $name; public function __construct(int $id, string $name) { $this->id = $id; $this->name = $name; } } $camelCase is not only Symfony's recomendation for code standard. It's based on PSR2. I highly recomend using PSR2, code gets clean and standarized. Standard ORM naming strategy is $camelCase private var to snake_case column name. If you want to change it otherwise, consider: other naming stategies
{ "language": "en", "url": "https://stackoverflow.com/questions/7573694", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How do I find out when the last party fires Phaser.arrive()? Given: Executor executor = ...; Phaser phaser = new Phaser(n); for (int i=0; i<n; ++i) { Runnable task = new Runnable() { public void run() { phaser.arriveAndDeregister(); if (lastTask) doSomething(this); } } // run tasks using a thread-pool (order is not guaranteed) executor.submit(task); } I'd like to find out if I'm the last task in order to fire doSomething() that depends upon the task's internal state. I found Phaser.onAdvance(int, int) but it's not clear how to use it in this case. A: I can't think of a very elegant way of solving this but the use of ThreadLocal and the onAdvance can help. final ThreadLocal<Boolean> isLast = new ThreadLocal<Boolean>() { public Boolean initialValue() { return false; } }; final Phaser p = new Phaser(9) { public boolean onAdvance(int phase, int registeredParties) { isLast.set(true); return true; } }; Then public void run() { phaser.arriveAndDeregister(); if (isLast.get()) doSomething(this); } A: Since you seem to know a priori how many tasks you have, just use a separate AtomicInteger. int n = 5; ExecutorService executor = ... final AtomicInteger count = new AtomicInteger (n); final Phaser phaser = new Phaser (n); for (int i = 0; i < n; ++i) { Runnable task = new Runnable () { public void run () { phaser.arriveAndDeregister (); if (count.decrementAndGet () == 0) { doSomething (this); } } }; // run tasks using a thread-pool (order is not guaranteed) executor.submit (task); } Or, if you need to call doSomething before dormant parties are notified, just override onAdvance and do it from there. final Phaser phaser = new Phaser (n) { protected boolean onAdvance(int phase, int registeredParties) { doSomething(this); return super.onAdvance(phase, registeredParties); } };
{ "language": "en", "url": "https://stackoverflow.com/questions/7573699", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: decimal numbers for padding and margin Can I use decimal numbers (18.9 or 75.5) for padding, margin or other styles? all browsers (such as IE5, IE6) support it? Thanks. A: As long as it's an EM measurement, I don't see why not. Not sure about IE5, but I'm pretty sure IE6 is supported for decimals. Any browser that supports EM. A: Yes, they apply anywhere for measurements. They don't make a lot of sense if you're positioning something and using partial pixel measurements, but otherwise they're perfectly acceptable. Just remembe to specify the units. e.g. height: 57; /* no units, will be treated as an error */ height: 57px; /* perfectly fine */
{ "language": "en", "url": "https://stackoverflow.com/questions/7573702", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Creating SQL Server login via script using variable I am trying to create a SQL Server login following the creation of a database through script. The login is local to the host PC and this script will be run on multiple hosts. What I want to do is the following: USING MyDatabase CREATE MyUser FOR LOGIN USER <computer name>/MyUser What I don't know how to do is incorporate the computer name (ex. Location0001) into this statement. The login does exist on each machine AND is already listed on the SQL Server as it has access to other databases there. If it's relevant, the script should be able to run on SQL Server 2008. The login would look like this for each machine: Location0001\MyUser Location0002\MyUser Location0999\MyUser Any help would be appreciate, thanks. Edit: My final solution based on the accepted answer is as follows: DECLARE @cmd VARCHAR(200) SET @cmd = N'CREATE USER [MyUser] FOR LOGIN [' + HOST_NAME() + '\MyUser]' EXEC (@cmd) A: You can use the @@servername property to get the name of the machine: select @@servername declare @cmd varchar(200), @username varchar(50) set @username = 'testuser' set @cmd = ' USE MyDatabase CREATE USER MyUser FOR LOGIN '+@@servername+'\'+@username PRINT @cmd EXEC (@cmd)
{ "language": "en", "url": "https://stackoverflow.com/questions/7573704", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How to specify generic type argument in XAML I have a BaseView for my MVP - PRISM WPF application. Now for some reason we thought to make the _presenter as a Templated field in the BaseView. earlier i had the view xaml representation as <base:BaseView xamlns:base="clr address of the dll which had BaseView" > </base:BaseView> now since i have changed the BaseView to BaseView<TPresenter>, So how shall i write the Xaml then? A: You can do it since .NET 4 Framework and XAML 2009. See Generics in XAML on MSDN For instance: <my:BusinessObject x:TypeArguments="x:String,x:Int32"/> For .NET 3.5: For XAML 2006 usage when specifically targeting WPF, x:Class must also be provided on the same element as x:TypeArguments, and that element must be the root element in a XAML document. The root element must map to a generic type with at least one type argument. An example is PageFunction. Possible workarounds to support generic usages include defining a custom markup extension that can return generic types, or providing a wrapping class definition that derives from a generic type but flattens the generic constraint in its own class definition. A: In case this happens to someone. I had a similar scenario where I converted my base class to a templated class (i.e. BaseView to BaseView). I kept receiving errors in the InitializeComponent() method. I was receiving the null exception error in the x:Class base type's InitializeComponent() call. I was able to resolve the errors by removing the form-level events from the XAML definition. If I had to keep the form-level events I would need to move them to BaseView.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573712", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Ruby not properly understand what gems are installed when running from Jenkins? I have a Jenkins job that is supposed to run. The job description is as follows: SVN update the workspace repository Run the following Windows batch command "ruby -d tester.rb" When I run this command from the command line on the master machine (which is a physical machine in front of me), the script runs no problem When I run a seperate job that calls "ruby -v", it sees the correct version of ruby. When I run a seperate job that calls "gem list", it sees the correct version of ruby. However when I run the job described at the top, I get errors that none of the gems listed as being installed by "gem list" are installed, and my script does not run. Can anyone provide a suggestion? for more information here is code from a run with a bit of a combination of the data: [workspace] $ cmd /c call C:\Windows\TEMP\hudson3791189246243258127.bat C:\Program Files (x86)\Jenkins\jobs\job1\workspace>ruby -r rubygems -e "p Gem.path" ["C:/Windows/system32/config/systemprofile/.gem/ruby/1.8", "C:/Ruby187/lib/ruby/gems/1.8"] C:\Program Files (x86)\Jenkins\jobs\job1\workspace>cd .qa_automation\trunk C:\Program Files (x86)\Jenkins\jobs\job1\workspace\.qa_automation\trunk>set GEM_HOME=c:\Ruby187\lib\ruby\gems\1.8 C:\Program Files (x86)\Jenkins\jobs\job1\workspace\.qa_automation\trunk>ruby -d _Tester.rb config\portalconfigPROD.txt compare_IWT_Main_TSS Exception `LoadError' at C:/Ruby187/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36 - no such file to load -- random_data Exception `NoMethodError' at C:/Ruby187/lib/ruby/1.8/rational.rb:78 - undefined method `gcd' for Rational(1, 2):Rational Exception `LoadError' at C:/Ruby187/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36 - no such file to load -- uuidtools Exception `NameError' at C:/Ruby187/lib/ruby/gems/1.8/gems/uuidtools-2.1.2/lib/uuidtools/version.rb:25 - uninitialized constant UUID Exception `LoadError' at C:/Ruby187/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36 - no such file to load -- builder ./lib/Portal/Session.rb:379: warning: statement not reached ./lib/Portal/Session.rb:434: warning: statement not reached Exception `LoadError' at C:/Ruby187/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36 - no such file to load -- selenium-webdriver Exception `LoadError' at C:/Ruby187/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36 - no such file to load -- yajl/json_gem Exception `LoadError' at C:/Ruby187/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:60 - no such file to load -- yajl/json_gem Exception `LoadError' at C:/Ruby187/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36 - no such file to load -- json/ext/parser Exception `LoadError' at C:/Ruby187/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:60 - no such file to load -- json/ext/parser Exception `LoadError' at C:/Ruby187/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:60 - no such file to load -- json/ext/parser Using Pure library for JSON. _Tester.rb:78: warning: already initialized constant ARGV C:/Ruby187/lib/ruby/gems/1.8/gems/selenium-webdriver-2.7.0/lib/selenium/webdriver/remote/capabilities.rb:171: warning: method redefined; discarding old proxy= C:/Ruby187/lib/ruby/gems/1.8/gems/ffi-1.0.9-x86-mingw32/lib/ffi/struct.rb:225: warning: discarding old align Exception `LoadError' at C:/Ruby187/lib/ruby/gems/1.8/gems/ffi-1.0.9-x86-mingw32/lib/ffi/library.rb:133 - LoadError Exception `LoadError' at C:/Ruby187/lib/ruby/gems/1.8/gems/ffi-1.0.9-x86-mingw32/lib/ffi/library.rb:133 - LoadError A: For a quick hack, try running the command "ruby -d tester.rb", with the file path to ruby where your gems are installed. So for example "/users/llaskin/lib/bin/ruby -d tester.rb". Also if you have used RVM to install your ruby and gems, and have installed multiple versions, rvm messes things up.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573714", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Error with Intents (Android) So this is supposed to be really really simple, since I'm just in the beginning stages of this app. Remember, I'm a beginner so excuse the noob code :p The app crashes (force close) whenever I click the button to go on to the next page. Code is given below: Button b = (Button) findViewById(R.id.button1); final EditText et1 = (EditText) findViewById(R.id.editText1); final EditText et2 = (EditText) findViewById(R.id.editText2); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent i = new Intent(User.this, Game.class); i.putExtra("p1", et1.getText().toString()); i.putExtra("p2", et2.getText().toString()); Toast.makeText(User.this, "Activity 2 about to launch", Toast.LENGTH_SHORT).show(); Toast.makeText(User.this, "Activity 2 launched", Toast.LENGTH_SHORT).show(); startActivity(i); } }); } } Next page is below: TextView tv = (TextView) findViewById(R.id.textView2); Button b1 = (Button) findViewById(R.id.button1); Button b2 = (Button) findViewById(R.id.button2); Button b3 = (Button) findViewById(R.id.button3); Button b4 = (Button) findViewById(R.id.button4); Button b5 = (Button) findViewById(R.id.button5); Button b6 = (Button) findViewById(R.id.button6); Button b7 = (Button) findViewById(R.id.button7); Button b8 = (Button) findViewById(R.id.button8); Button b9 = (Button) findViewById(R.id.button9); public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.game); Toast.makeText(Game.this, "Welcome "+getIntent().getExtras().getString("p1")+" and "+getIntent().getExtras().getString("p2"), Toast.LENGTH_SHORT).show(); } A: You cannot use findViewById before onCreate (and this is what you are doing if you try to initialise with a value like that). You should also not try to resolve your views before you have called setContextView since they are not part of your layout before this time. You can only 'find' them once they have been added. Move the initialising code to inside the onCreate method: public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.game); TextView tv = (TextView) findViewById(R.id.textView2); Button b1 = (Button) findViewById(R.id.button1); Button b2 = (Button) findViewById(R.id.button2); Button b3 = (Button) findViewById(R.id.button3); Button b4 = (Button) findViewById(R.id.button4); Button b5 = (Button) findViewById(R.id.button5); Button b6 = (Button) findViewById(R.id.button6); Button b7 = (Button) findViewById(R.id.button7); Button b8 = (Button) findViewById(R.id.button8); Button b9 = (Button) findViewById(R.id.button9); Toast.makeText(Game.this, "Welcome "+getIntent().getExtras().getString("p1")+" and "+getIntent().getExtras().getString("p2"), Toast.LENGTH_SHORT).show(); } A: I see one obvious problem. From Intent.putExtra: Add extended data to the intent. The name must include a package prefix, for example the app com.android.contacts would use names like "com.android.contacts.ShowAll". i.putExtra("p1", et1.getText().toString()); "p1" does not have a package prefix! So, this may work, may not work, crash, or demons may fly out of your nose. You should change "p1" to something like "com.myfirstandroid.p1", assuming the package is called "com.myfirstandroid". I can't be sure if this is your exact problem. You should include the reason of the crash for more specific answers. Have look at the LogCat. A: A really common way to crash your application (especially when you are new to Android) is by forgetting to declare an Activity in your manifest file. I'm betting that this has caused your error. Your code looks good, and it should start the Game Activity. However, even if you have properly defined the Game class, it will not work unless you declare Game in your manifest file. Your manifest should already include some code about your original Activity that looks something like this: <activity android:name=".YourApplication" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> This declares a new activity and adds some filters to make sure it is the first thing opened when you launch the application. You should make sure you add a line like this right below it, so that the system knows about your Game class <activity android:name=".Game" android:label="Game"> For future reference and debugging more complex errors, you will want to know about the LogCat. The logcat usually makes fixing errors incredibly simple. When you get an error, the logcat output in Eclipse typically looks like this 07-25 13:19:10.593: ERROR/AndroidRuntime(22861): FATAL EXCEPTION: main ERROR/AndroidRuntime(22861): java.lang.RuntimeException: /some sort of error/ .../A lot of description/ ... 07-25 13:19:10.593: ERROR/AndroidRuntime(22861): Caused by: /Whatever the specific error was/ 07-25 13:19:10.593: ERROR/AndroidRuntime(22861):at com.chris.formStuff.FormStuffActivity.onCreate(FormStuffActivity.java:25) ... ... When you get errors like this you want to look at the "Caused by..." line, and the first few after that. This will describe the error and give you the exact line it occurred at.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573717", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Update ASP.NET Page after GridView DataBind EDIT: Apparently, part of the problem is that while an ASP:GridView has an OnDataBound() event (which you can use in the code-behind), the corresponding HTML table that is produced does NOT, so you can attach that event to JavaScript. (Did I get that right?) So, that's why I'm having trouble with that bit of the issue. Back to the drawing board. I'm a desktop developer (WinForms with VB.NET) transitioning into ASP.NET development. My mind is really bending around the DOM and JavaScript and Session State and all of the stuff that goes along with web development. I'm not stupid, and I've done research (including hours of video watching and hundreds of pages of "Intro to ASP.NET" reading), but I keep hitting the wall with what seem to be fairly straightforward problems. Basically, my current situation can be summed up as follows: * *I have a page that runs a very long process initiated by the user. *The long process can take up to a few minutes , so I want to indicate to the user that SOMETHING is happening. *When the process has completed, I either have: a. Results to show in a GridView b. No results to show *If I have results to show, I want to display them. *If I have no results to show, I want to show a label to the user that says "No results to show." What's working: * *I have a basic page where the user selects start and end dates and kicks off the check process. *The check process works fine (using LINQ-to-SQL logic developed for a desktop version of this program). *I've got an UpdatePanel on my page which shows a label and an animated gif to indicate that something's happening. *If I get results, they display appropriately in my GridView. What's not working: * *I'd love to give the user some sort of progress bar to indicate actual progress made toward completion rather than some endlessly-animating gif that doesn't indicate much at all. I could calculate this value quickly and easily, but can't figure out how to transfer said value from server to web page. *I can't figure out how to trigger an "unhide" event for the label. The long-running process is in a button's click event handler, where I run my custom code and generate a DataTable, which I then save as a session variable, assign it as the GridView's DataSource and call GridView.DataBind(). When I try to determine the contents of the DataTable and hide/reveal the label there, nothing seems to happen. Problem #2 is really what I need to figure out in order to publish this web site. I'm assuming it involves a JavaScript solution, and I've tried some stuff, but I find that I'm truly guessing and don't have a good grasp on what the solution should resemble. Here's the label I'd like to selectively reveal/make visible: <tr> <td colspan="2" align="center"> <h2><asp:Label runat="server" ID="lblNoMissing" Text="No Missing Documentation Found" Visible="false"></asp:Label></h2> </td> </tr> Here's a JavaScript function I'm trying to test: <script type="text/javascript"> function databound() { var gridViewID = '<%=_gridView1.ClientID%>'; var labelID = '<%=lblNoMissing.ClientID%>'; var gridView = document.getElementById(gridViewID); if (gridView.rows.length > 0) { $get(labelID).style.visibility = "false"; } else { $get(labelID).style.visibility = "true"; } } </script> Problem: This fails (databound not a member of Default.aspx): <asp:GridView ID="_gridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="Horizontal" PageSize="20" OnDataBound="databound();"> // Rest of GridView definition removed </asp:GridView> What am I missing? Thanks!!!! A: For #2, set style.visibility="visible" See: http://www.w3schools.com/cssref/pr_class_visibility.asp for valid values. For #1, you can use an update panel with a timer for refreshing it. The server can simply add the current status to that users Session. The update panel code reads the session and shows the result. A: For problem #1, there are a whole bunch of free Javascript progress bars out there. As for your value that you can't retrieve, try this: <asp:Label ID="ProgressValue" runat="server" visible="false" /> And in your code behind. ProgressValue.Text = //Your value from your database. And just reference it from your Javascript there. For your second problem, can't you just do in your code behind (written in C#) //Process here if(IDofGridView.Rows != null) { lblNoMissing.Visible = true; } Or am I missing something? A: So, I'm not sure I solved this exactly the way I wanted, but I have a working version. Here's what I did (for others who might find this useful): * *I have abandoned my plans for #1 for now. I just simply don't have the time to continue looking into this issue right now. I'm bummed, though, because it seems like this is something a lot of people need to do, but I can't find a cookie cutter solution. Seems weird to me. Maybe I'm still missing some key info that would make it easy. *I have a GridView, a progress Label, an animated gif and a "no results" Label that I want to show/hide at various times. What ended up working for me was to place them all in UpdatePanels and simply show/hide them in my code-behind. It's kind of starting to make sense, but changing the visibility of a control from the code-behind when the control to change is OUTSIDE of an UpdatePanel but the code is initiated FROM INSIDE an UpdatePanel seems like a barrier that can't be crossed. That is, when my "no missing" Label was OUTSIDE of an UpdatePanel, the long-running process (started by a button INSIDE the UpdatePanel) couldn't change its visibility. (Does that make sense? Anyone want to correct that?) Thanks for reading! Thanks for the ideas! Edit: OK, so I'm apparently wrong again. The code that shows/hides my Label and GridView has nothing to do with any code executed in the long-running process in the code-behind file. Here's the code that actually does what I want (code is in Default.aspx): <script type="text/javascript" > Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(CheckStatus); function CheckStatus(sender, args) { var prm = Sys.WebForms.PageRequestManager.getInstance(); if (prm.get_isInAsyncPostBack()) { args.set_cancel(true); // stop request from being sent $get("_messageSpan").innerHTML = "<h2>The last request is still processing.</h2>"; } else { var lbl = document.getElementById('<%=lblNoMissing.ClientID%>'); if (lbl) { lbl.style.visibility = "hidden"; } var gview = document.getElementById('<%=_gridView1.ClientID%>'); if (gview) { gview.style.visibility = "hidden"; } $get("_messageSpan").innerHTML = ""; } } </script> The code related to "_messageSpan" is to prevent subsequent button clicks from starting the long-running process again (and also notify the user that it's still running). So, since it is never correct for either of my items to be showing during a non-AsyncPostBack, I simply try to get the items and, if I get them, set them hidden. Now my page is behaving correctly. This may be some hacky code, but the page at least looks the way I want it!
{ "language": "en", "url": "https://stackoverflow.com/questions/7573719", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: NSBox background image How can I set background image a for an NSBox? I know we can put a color, but what about background image? A: Check out +NSColor colorWithPatternImage:. [myNSBox somehowSetBackgroundColor: [NSColor colorWithPatternImage: myImage]];
{ "language": "en", "url": "https://stackoverflow.com/questions/7573720", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can i display an array outside the for each loop? So I have a shopping cart that works fine, but I want to display the results of the shopping cart inside a contact form outside of the for each loop. The problem I am having is whenever I try to display $Ptitle it just displays the last addition to the shopping cart. Not the full list of titles inside the array. I have tried various methods to display the array results, but none seem to work. And it seems i can print the array via print_r ($contents); But only inside the for each loop, not outside. Below is the code, sorry if it's messy. Any help would be appreciated. Thank you! function showCart() { global $db; $cart = $_SESSION['cart']; if ($cart) { $items = explode(',',$cart); $contents = array(); foreach ($items as $item) { $contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1: 1; } echo '<form action="http://www.changecompanies.net/dev/theme/cart_checkout.php?action=update" method="post" id="cart">'; //$output[] = '<table>'; ?> <table id="cart"> <tr> <th>Quantity</th> <th></th> <th>Item</th> <th>Product Type</th> <th>Unit Price</th> <th>Total</th> <th>Remove</th> </tr> <?php foreach ($contents as $id=>$qty) { $sql = 'SELECT * FROM tccproducts WHERE id = '.$id; $result = $db->query($sql); $row = $result->fetch(); extract($row); $result = mysql_query("SELECT * FROM tccproducts WHERE Pid ='$id'")or die (mysql_error()); //if (!$result); //echo "no result"; $myrow = mysql_fetch_array($result) or mysql_error('error!'); $name = $myrow['Ptitle']; //$name = substr($name,0,40); $Pprice = $myrow['Pprice']; $Ptitle = $myrow['Ptitle']; $Pimage = $myrow['Pimage']; $Pcat = $myrow['Pcategory']; $mini = $myrow['Pminimum']; Rest just displays the cart and ends the for each loop. A: You're running a loop on all the items in the cart, fetching details about that item, then storing the details in individual variables. On every iteration of the loop, the data you retrieve previously gets overwritten by the next row of data fetched. As such, you only ever store the data from the LAST item fetched. If you want to store all of the item data, you'll have to store each row in an arrow and output afterwards, or just output each row as it's fetched. while($row = mysql_fetch(...)) { echo <<<EOL <tr> <td>{$quantity}</td> <td>{$row['price']}</td> etc... </tr> EOL; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7573721", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Django template get custom attribute from request OR "refresh" radio buttons I currently have a template containing an html form, with the lines: {% for r in q1.responseoption_set.all %} <span class="r"><input type="{{ q1.answer_type }}" name="r{{ r.id }}" id="r{{ forloop.counter }}"/> <label {% if q1.answer_type == "text" %}class="textanswer"{% endif %}for="r{{ forloop.counter }}">{{ r.text }}</label></span><br> {% endfor %} problem is, because they don't all have the same name (that's why, right?), if I pick a radio button, and then switch to another one, the first one still shows as selected. However, at the moment, I need them to all have different names because I need to be able to identify the choices within my view, and as far as I can tell, all I can get from the request is [name, value], e.g. [r200, "on"] The only way around this that I can think of is to insert a script that assigns a check event to each button, and then, once checked, inserts a hidden input with the name I want, but that seems messy. SO, is there a way for me to either: get the button id from the request OR have the buttons "refresh" somehow as they are. A: Keep the name the same, and set the value for each input choice to the answer id. {% for r in q1.responseoption_set.all %} <span class="r"><input type="{{ q1.answer_type }}" name="{% questionId %}" value="r{{ r.id }}" id="r{{ forloop.counter }}"/> <label {% if q1.answer_type == "text" %}class="textanswer"{% endif %}for="r{{ forloop.counter }}">{{ r.text }}</label></span><br> {% endfor %}
{ "language": "en", "url": "https://stackoverflow.com/questions/7573723", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SQL Method of checking that INNER / LEFT join doesn't duplicate rows Is there a good or standard SQL method of asserting that a join does not duplicate any rows (produces 0 or 1 copies of the source table row)? Assert as in causes the query to fail or otherwise indicate that there are duplicate rows. A common problem in a lot of queries is when a table is expected to be 1:1 with another table, but there might exist 2 rows that match the join criteria. This can cause errors that are hard to track down, especially for people not necessarily entirely familiar with the tables. It seems like there should be something simple and elegant - this would be very easy for the SQL engine to detect (have I already joined this source row to a row in the other table? ok, error out) but I can't seem to find anything on this. I'm aware that there are long / intrusive solutions to this problem, but for many ad hoc queries those just aren't very fun to work out. EDIT / CLARIFICATION: I'm looking for a one-step query-level fix. Not a verification step on the results of that query. A: If you are only testing for linked rows rather than requiring output, then you'd use EXISTS. More correctly, you need a "semi-join" but this isn't supported by most RDBMS unless as EXISTS SELECT a.* FROM TableA a WHERE EXISTS (SELECT * FROM TableB b WHERE a.id = b.id) Also see: * *Using 'IN' with a sub-query in SQL Statements *EXISTS vs JOIN and use of EXISTS clause A: SELECT JoinField FROM MyJoinTable GROUP BY JoinField HAVING COUNT(*) > 1 LIMIT 1 Is that simple enough? Don't have Postgres but I think it's valid syntax. A: Something along the lines of SELECT a.id, COUNT(b.id) FROM TableA a JOIN TableB b ON a.id = b.id GROUP BY a.id HAVING COUNT(b.id) > 1 Should return rows in TableA that have more than one associated row in TableB.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573745", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Ryan Dahl's Node Chat Can someone explain in details the Node Chat written by Ryan Dahl. It used the core Node.js methods without using the Socket.io. I've searched a lot for the documented version. I couldn't find one. Can someone please help me with that. A: Even I've been looking for such a solution. The best one out there is https://github.com/neerajdotname/node-chat-in-steps This guy explains it in steps. I found it very helpful. At least to a very good extent.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573746", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Looking for guidance on multi-part graphical gesture recognition I'm trying to research existing works in the area of recognizing complex graphical gestures, but struggling to find good search terms or clear documents in the field. For example, I might want to recognize an arbitrary shape drawn by a mouse as a path, or a path with an arrow head, or an enclosed region, or some combination of various shapes. One of the problems I'm having is that the shapes are not necessarily going to take a consistent symbolic form, so I'm looking for alternate ways to represent the data. This article has been helpful so far, but does not discuss any concrete algorithms. http://www.springerlink.com/content/l4235612gv479262/ Anyway, I'm not necessarily looking for solutions here (though I'd be interested if there were some), but if people can help direct me towards some pertinent papers or the right kinds of search terms, I would appreciate it! A: If you take the sequence in which the gesture is made/drawn into account then you might want to make use of sequence alignment techniques. Asking Google gives quite a few matches which you might want to explore.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573747", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Javascript null coalescing help, how can I incorporate a threshold value? a = b || c but if b > d, choose c I want to assign a value to a variable in javascript var a = b || c; //however if b > 200 choose c Is there a simple way to do this? var a = (b && b <= 200) ? b : c; Thanks for any tips or advice. Just trying to write this as cleanly as possible. A: var a = b; if(b == undefined || b > 200){ a = c; } A: You can simplify it even more: var a = b<=200 && b || c; Or, more readable, var a = ( b<=200 && b ) || c; Explanation: * *You can use && to get the first falsy value or, if there isn't any, the last truly one. *You can use || to get the first truly value or, if there isn't any, the last falsy one. Therefore: * *If b is falsy Then, b<=200 && b is falsy, so b<=200 && b || c gives c *If b is truly * *If b<=200 Then, b<=200 && b gives b, which is truly, so b<=200 && b || c gives b too. *If b>200 Then, b<=200 && b gives false, which is falsy, so b<=200 && b || c gives c. Some tests: 100<=200 && 100 || 50 // 100, because 100 is truly and 100<=200 150<=200 && 150 || 50 // 150, because 150 is truly and 150<=200 '150'<=200 && '150' || 50 // '150', because '150' is truly and 150<=200 300<=200 && 300 || 50 // 50, because 300<=200 is false (but 300 is truly) 'abc'<=200 && 'abc' || 50 // 50, because NaN<=200 is false (but 'abc' is truly) ({})<=200 && ({}) || 50 // 50, because NaN<=200 is false (but {} is truly) false<=200 && false || 50 // 50, because false is falsy (but 0<=200) null<=200 && null || 50 // 50, because null is falsy (but 0<=200) ''<=200 && '' || 50 // 50, because '' is falsy (but 0<=200)
{ "language": "en", "url": "https://stackoverflow.com/questions/7573749", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Google maps and shadowbox I'm building a javascript function that load google maps inside shadowbox, this is quite easy using this code (I used the plugin calld GeoPlugin to get latitude and longitude, because I don't now how to get my lat and long automatically): function initGeoLocationOnDemand() { $('a.btnInitGeoLoc').click(function () { if (GBrowserIsCompatible()) { Shadowbox.open({ player: "html", content: "", height: 300, width: 500, options: { onFinish: function (item) { var body = document.getElementById(Shadowbox.playerId); var map = new GMap2(body); //using geoPlugin to get lat and long var point = new GLatLng(geoplugin_latitude(), geoplugin_longitude()); map.setCenter(point, 15); var marker = new GMarker(point); var addrFields = ['street_address']; map.addOverlay(marker); marker.openInfoWindow(document.createTextNode("hello"); // add some simple controls map.addControl(new GSmallMapControl()); map.addControl(new GMapTypeControl()); } } }); } else { alert("Your browser is not compatible with Google Maps!"); } }); Shadowbox.init(); } Now I would like tu use GoogleMaps Reverse Geocoding to get inside the information window in googleMaps marker information like: city name, country name, street name, postal code, etc... I did this code, following GoogleMaps api, but it doesn't work anymore... always using GeoPlugin: function initGeoLocationOnDemand() { $('a.btnInitGeoLoc').click(function () { if (GBrowserIsCompatible()) { Shadowbox.open({ player: "html", content: "", height: 300, width: 800, options: { onFinish: function (item) { var body = document.getElementById(Shadowbox.playerId); var geocoder; var map = new google.maps.Map(body); var infowindow = new google.maps.InfoWindow(); var marker; function initialize() { geocoder = new google.maps.Geocoder(); var latlng = new google.maps.LatLng(geoplugin_latitude(),geoplugin_longitude()); var myOptions = { zoom: 8, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP } map = new google.maps.Map(body, myOptions); } function codeLatLng() { var input = document.getElementById("latlng").value; var latlngStr = input.split(",", 2); var lat = parseFloat(latlngStr[0]); var lng = parseFloat(latlngStr[1]); var latlng = new google.maps.LatLng(lat, lng); geocoder.geocode({ 'latLng': latlng }, function (results, status) { if (status == google.maps.GeocoderStatus.OK) { if (results[1]) { map.setZoom(11); marker = new google.maps.Marker({ position: latlng, map: map }); infowindow.setContent(results[1].formatted_address); infowindow.open(map, marker); } } else { alert("Geocoder failed due to: " + status); } }); } } } }); } else { alert("Your browser is not compatible with Google Maps!"); } }); Shadowbox.init(); } There is a way to get latitude and longitude without using plugins? There is a way to get information about Country name, City name, street name, postal code, etc? Thanks in advance for your help! A: Latitude and longitude of what place do you want? The client machine? A: I am not familiar with Shadowbox, but there is surely at least one problem in handling the results of the Geocoder. You should use results[0] instead of results[1] to get the first (if any) reverse geocode of latlng.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573750", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery find() until? I'm going through a form checking values but I need to stop before a specific element (#before) $('#before').closest('form').find('.reqd').each(function() { //chacks input }); I need this to stop before or even better after it reaches #before. I read about nextUntil() but it seems only to work for sibling elements. I need to check all .reqd elements in the form before #before I bet I'm missing some really simple way to do it. A: returning false within an each loop will exit the each loop. $('#before').closest('form').find('.reqd').each(function() { // your code here if (this.id === "before") { // end each loop after processing #before return false; } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7573751", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Selecting values from one column based on a different columns value Having trouble stating my problem succinctly here, so I'll just give an example. Let's say I have a DB2 table about Students: Name Class Grade Billy J Econ A Sarah S Maths B Greg X Computes A- Billy J Maths D Greg X Maths C+ And I want to retrieve those students that are in both Econ and Maths, and display the information thusly: Name Maths Grade Econ Grade Billy J D A How in the world can I accomplish this? A: This solution will solve the problem for the two classes you named: SELECT Name, Math.Grade AS MathsGrade, Econ.Grade AS EconGrade FROM Students Math INNER JOIN Students Econ ON Math.Name = Econ.Name WHERE Math.Class = 'Maths' AND Econ.Class = 'Econ' The only thing that this solution doesn't do is include the spaces in your derived column names. You can do that by writing Maths Grade and Econ Grade in whatever characters DB2 uses for identifier quotes. To be included students must have both a Maths and an Econ grade. A: SELECT * from Students where id in (SELECT id from Students where Class = 'Econ') AND id in (SELECT id from Students where Class = 'Math');
{ "language": "en", "url": "https://stackoverflow.com/questions/7573753", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to use CAPI's CryptImportKey with PEM encode public key from OpenSSL? How do I get the Microsoft's CryptoAPI CryptImportKey function to import a PEM encoded key? It actually works but CryptDecrypt returns an error. // 1. Generate a Public/Private RSA key pair like so: openssl genrsa -out private.pem 2048 openssl rsa -in private.pem -out public.pem -outform PEM -pubout // 2. Create a digital signaure using OpenSSL // Load Private key // -----BEGIN RSA PRIVATE KEY----- // BLAHBLAHBLAH // -----END RSA PRIVATE KEY----- // Concat user details std::string sUser = "John Doe | Business | john@na.com | 1316790394 | 0 | 1 | ProductName | 1"; // Get a one-way hash of it. SHA1((const unsigned char *) sUser.c_str(),sUser.size(), hash); // Create the digital signature ~ PKCS #1 v2.0 format (also known as OAEP encryption) RSA_sign(NID_sha1, hash, SHA_DIGEST_LENGTH, pbData, &iDataLen, rsa_key); // 3. Verify the signature using Windows CryptoAPI // Load Public key // -----BEGIN PUBLIC KEY----- // BLAHBLAHBLAH // -----END PUBLIC KEY----- // Convert from PEM format to DER format - removes header and footer and decodes from base64 CryptStringToBinaryA((char*)pbPublicPEM, iPEMSize, CRYPT_STRING_ANY, pbPublicDER, &iDERSize, NULL, NULL); // Decode from DER format to CERT_PUBLIC_KEY_INFO. This has the public key in ASN.1 encoded // format called "SubjectPublicKeyInfo" ... szOID_RSA_RSA // Do I need to get the "public key" and "modulus" from this format and build a PUBLICKEYBLOB manually? CryptDecodeObjectEx( X509_ASN_ENCODING, X509_PUBLIC_KEY_INFO, pbPublicDER, iDERSize, CRYPT_ENCODE_ALLOC_FLAG, NULL, &pbPublicPBLOB, &iPBLOBSize ); // decode the RSA Public key itself to a PUBLICKEYBLOB ? CryptDecodeObjectEx( X509_ASN_ENCODING, RSA_CSP_PUBLICKEYBLOB, pbPublicPBLOB->PublicKey.pbData, pbPublicPBLOB->PublicKey.cbData, CRYPT_ENCODE_ALLOC_FLAG, NULL, &pbPKEY, &iPKEYSize ); // Get a context CryptAcquireContext(&hCryptProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT); // load the key CryptImportKey(hCryptProv, pbPKEY, iPKEYSize, 0, CRYPT_OAEP, &hKey); // Verify the signature CryptDecrypt(hKey, 0, TRUE, 0, pbData, &iDataLen); // CryptDecrypt returns NTE_NO_KEY -2146893811 0x8009000D A: You are using the wrong APIs. RSA_sign() signs a hash; use CryptVerifySignature() to verify it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7573754", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }