text
stringlengths
8
267k
meta
dict
Q: Adding a property to a silverlight 4 control to add functionality I am curious how I can add a property to add functionality to a control. Currently I am just extending controls, but I was curious if it is possible to add a property to add functionality to a control. Like for example the ToolTipService. You can add that to controls. Would it be possible for me to add a property to add a contextmenu without having to extend a textbox lets say? I know about behaviors, but is it possible to do that as a property? Let's say I add a property IsContextMenuBehaviorAdded="True" and that will just attach a behavior, or just add functionality. Any help would be greatly appreciated. Thanks in advance. A: If you are looking to add a context menu to a control then you can do that with the Silverlight Toolkit which contains a ContextMenuService.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615757", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get index from a list where the key changes, groupby I have a list that looks like this: myList = [1, 1, 1, 1, 2, 2, 2, 3, 3, 3] What I want to do is record the index where the items in the list changes value. So for my list above it would be 3, 6. I know that using groupby like this: [len(list(group)) for key, group in groupby(myList)] will result in: [4, 3, 3] but what I want is the index where a group starts/ends rather than just then number of items in the groups. I know I could start summing each sucessive group count-1 to get the index but thought there may be a cleaner way of doing so. Thoughts appreciated. A: [i for i in range(len(myList)-1) if myList[i] != myList[i+1]] In Python 2, replace range with xrange. A: Just use enumerate to generate indexes along with the list. from operator import itemgetter from itertools import groupby myList = [1, 1, 1, 1, 2, 2, 2, 3, 3, 3] [next(group) for key, group in groupby(enumerate(myList), key=itemgetter(1))] # [(0, 1), (4, 2), (7, 3)] This gives pairs of (start_index, value) for each group. If you really just want [3, 6], you can use [tuple(group)[-1][0] for key, group in groupby(enumerate(myList), key=itemgetter(1))][:-1] or indexes = (next(group)[0] - 1 for key, group in groupby(enumerate(myList), key=itemgetter(1))) next(indexes) indexes = list(indexes) A: >>> x0 = myList[0] ... for i, x in enumerate(myList): ... if x != x0: ... print i - 1 ... x0 = x 3 6
{ "language": "en", "url": "https://stackoverflow.com/questions/7615758", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Getting Manufacturer and Modal # from XP Home with Java or the Command Line How can I get the Manufacturer and the Modal Number of an XP Home computer? I asked a similar question 3 months ago here. The answers were very helpful, but Windows XP Home Premium Edition does not have wmic or systeminfo. I looked in the registry on a few machines and did not find any consistent patterns. Do you have any ideas? I'd like to stick with Java and the Command Line. A: REG QUERY HKLM\HARDWARE\DESCRIPTION\System\BIOS -v SomeValueName gives you some info about the system, depending on what you use for SomeValueName. SystemProductName returns the model of my laptop. BaseBoardProduct has the same value, but it's entirely possible that the two will differ on some machines. One of those should give you a model number. SystemManufacturer and BaseBoardManufacturer have the name of my laptop's manufacturer. Again, the two might differ. You might be able to get the info by querying HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\OEMInformation, namely the "Model" and "Manufacturer" values. But that looks like info that'd be stored during an OEM install (like when you use Dell's install disc to reinstall Windows on your machine), and may not be present (or may be useless) on home-built systems. Note, the stuff returned by REG QUERY is in a particular format that you may need to parse. It's not complex, but REG QUERY /? doesn't seem to mention a way to get rid of the headers and the REG_SZ and such that get returned. (Also note: This is probably obvious to you...but the instant you use Runtime.exec to execute programs to query the Windows registry, you tie yourself to Windows.) A: Use Runtime.getRuntime().exec() to execute the appropraite windows command that inspects the registry, capture the output and parse it for the information you need.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615760", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Retrieving a list of Grails composite id properties? How can I retrieve a list of Grails composite id properties? I have tried the following but the id property is returning a Long: Domain class Domain implements Serializable { String field1 String field2 static mapping = { id composite: ['field1', 'field2'] } } Test def d = DefaultGrailsDomainClass(Domain.class) assert(d.identifier.type == java.lang.Long) A: After deep diving GORM I found the solution: GrailsDomainBinder.getMapping(Domain).identity.propertyNames
{ "language": "en", "url": "https://stackoverflow.com/questions/7615761", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: export to excel from sharepoint - complex There is some code/werbparts on our site that display a lot of data in a grid on our site. In addition, they have another page with a few charts. I need a way to create functionality to export this to excel so the user can click a button and save everything. The chart will actually have to be built in excel, I can't just grab the picture from the website and display it. Also, the data from the grid will have to be put into a spreadhseet. I am not as worried about this part. I have exported to excel before, but it was just basically printing some data which was tab delimited with a certain doc type . This actually will need to use different work sheets and use some excel functionality. (I need a better answer than use excel services) Thanks! A: Use Epplus is a third party library for creating and manipulating excel files(xlsx) A: Dunno about sharepoint, but the OpenXML SDK might be what you're after:- http://msdn.microsoft.com/en-us/library/bb448854.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7615762", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Tab menu overlaps I made a CSS menu but the individual tabs, or rather a row of tabs, seems to be overlapping each other. I used white-space: pre-wrap with a width on the tab menu itself: html > body > div#header > div#header-bottom-left > ul.tabmenu { position: absolute; top: 75px; left: 700px; width: 620px !important; } #header #header-bottom-left .tabmenu li { font-family: "Courier New", Courier, monospace !important; text-transform: uppercase; letter-spacing: 2px; font-variant: small-caps; font-size: 11px; padding: 5px; margin-right: 16px; background: url(%%buttons%%) repeat-x; border: 1px solid black; white-space: pre-wrap; margin-bottom: 20px; } A: In general, don't style the LI for menus, style the A tag and use display:block or inline-block A: not sure if this is what you want but I think you may be missing a float: left in your li code: http://jsfiddle.net/vT5vd/ BTW lists are fantastic for menus and are used so almost exclusively! A: The tabs are treated just like a line of text. The line spacing is set to the height of the text, causing the larger tabs to overlap. To correct this just add a line-height: 1.8; line to the css file in the tabs list item section. Also. you can put a break or paragraph tag in the list of tabs to control where they wrap to the next line and avoid splitting a tab. ul.tabs li a { font: normal 18px Verdana; line-height: 1.8; text-decoration: none; position: relative; padding: 0px 8px; border: 1px solid #CCC; border-bottom-color:#AAA; color: #000; background: #F0F0F0 url(tabbg.gif) repeat-x 0 0; border-radius: 2px 2px 0 0; outline:none; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7615764", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to leverage Custom Styles & Markup Styles in the SharePoint 2010 CEWP (100% JavaScript Solution) In short, with a RichHtmlField we can customize which Styles & Markup Styles appear in the drop down lists on the Ribbon. Using an OOTB Content Editor Web Part we cannot. After interrogating / contrasting the RichHtmlField vs. CEWP (HTML/JavaScript emitted) I was indeed able to find a JavaScript solution. While the RichHtmlField emits a Page Script to initialize the field control, the CEWP emits no such initialization script. Moreover, the RichHtmlField emits a significantly greater number of HTML Attributes than the CEWP does, and two of those attributes are PrefixStyleSheet and StyleSheet. PrefixStyleSheet identifies the style sheet prefix being used in the drop down menu. StyleSheet is a server relative url to the branded css file. So, with all these things being true, we should be able to initialize a CEWP with a branded stylesheet using jQuery: <script type="text/javascript"> ExecuteOrDelayUntilScriptLoaded(function() { // window.setTimeout(function() { $("div[RteRedirect]").each(function() { var id = $(this).attr("RteRedirect"), editSettings = $("#" + id); if(editSettings.length > 0 && editSettings[0].PrefixStyleSheet != 'yourcustom-rte') { editSettings[0]['PrefixStyleSheet'] = 'yourcustom-rte'; editSettings[0]['StyleSheet'] = '\u002fStyle Library\u002fen-US\u002fThemable\u002fCore Styles\u002f<somecustomstylesheet>.css'; RTE.Canvas.fixRegion(id, false); } }); // }, 2000); }, "sp.ribbon.js"); </script> I hope this helps someone. This code could go a lot of different directions. I'm merely presenting the fundamentals. If you add this to a master page inside an EditModePanel it will work cross site. There is a timer in there as depending on the order of script loading something may mess with what you've done after you've done it. Let me know if this works / doesn't work for you. Would be cool to keep a running tally of solutions to this problem somewhere. Cheers, M A: believe it or not 4 years late this post was helpfull ! To make it work I had to change this : $("td[RteRedirect]").each(function() { var id = $(this).attr("RteRedirect"); editSettings = $("#" + id); Thank you
{ "language": "en", "url": "https://stackoverflow.com/questions/7615767", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Hibernate composite key id generator I have my entities as below. My data model enforces below and I cannot change referential itegrity. So I am stuck with a composite key. I want to autogenerate/use some generator for orderId Yes I have read below. http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/#entity-mapping-identifier I donot want to manage the id generation process as above recommends application generating the orderId. How to make the partial id generator work.. what are my options..would greatly appreciate some thoughts by experts. @Entity @Table(name = "Orders", uniqueConstraints = @UniqueConstraint(columnNames = {"partner_ID", "order_ident" })) public class Order { private OrderId id; public Order() { } @EmbeddedId @AttributeOverrides({ @AttributeOverride(name = "partnerId", column = @Column(name = "partner_ID", nullable = false)), @AttributeOverride(name = "employeeId", column = @Column(name = "employee_ID", nullable = false)), @AttributeOverride(name = "orderId", column = @Column(name = "order_ID", nullable = false)) }) public OrderId getId() { return this.id; } public void setId(OrderId id) { this.id = id; } } @Embeddable public class OrderId extends FactObject { private int partnerId; private int employeeId; private int orderId; public OrderId() { } public OrderId(int partnerId, int employeeId, int orderId) { this.partnerId = partnerId; this.employeeId = employeeId; this.orderId = orderId; } @Column(name = "partner_ID", nullable = false) public int getpartnerId() { return this.partnerId; } public void setpartnerId(int partnerId) { this.partnerId = partnerId; } @Column(name = "employee_ID", nullable = false) public int getemployeeId() { return this.employeeId; } public void setemployeeId(int employeeId) { this.employeeId = employeeId; } @Id @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SEQ_STORE") @Column(name = "order_ID",insertable=false, nullable=false, updatable=false) public int getOrderId() { return this.orderId; } public void setOrderId(int orderId) { this.orderId = orderId; } public boolean equals(Object other) { if ((this == other)) return true; if ((other == null)) return false; if (!(other instanceof OrderId)) return false; OrderId castOther = (OrderId) other; return (this.getpartnerId() == castOther.getpartnerId()) && (this.getemployeeId() == castOther.getemployeeId()) && (this.getOrderId() == castOther.getOrderId()); } public int hashCode() { int result = 17; result = 37 * result + this.getpartnerId(); result = 37 * result + this.getemployeeId(); result = 37 * result + this.getOrderId(); return result; } } A: I have been hovering over all the possible links on World Wide Websites and trying to find why you cannot use @GeneratedValue with @EmbeddedId or @IdClass (i.e. composite PKs). The reason is that you just CANNOT. An explanation provided here might help you feel a bit better: JAVA.NET/GLASSFISH Composite PKs are ASSIGNMENT-based not GENERATION-based. Therefore, any @GeneratedValue stuff are not supposed to work with them. I am also having problem in my project and I think there is no other way, EXCEPT: If you know that your @GeneratedValue ID is always unique in context of your domain (for example, your database) you don't need to use composite PK and have some internal checks to determine the uniqueness of your records (i.e. persistence object collections). A: I think this question of stackoverflow might help you. Although it was asked for different purpose, it has the answer you might need. It has used both composite primary key and generation type. A: Generation strategy of composite primary key can be managed by @IdClass. Annotate the class with @IdClass for which you need composite pk. Annotate the fields that make for composite pk with @Id and @GeneratedValue. This works. e.g. @Entity @IdClass(B.class) Class A { @Id @GeneratedValue(strategy=GenerationType.AUTO) private int i; @Id @GeneratedValue(strategy=GenerationType.AUTO) private int j; private String variable; } Class B implements Serializable{ private int i; private int j; public int geti(){return i;} public int getj(){return j;} } In this example, combination of i and j will work as composite primary key for A. Their values are auto generated. A: Isn't using @IdClass a solution? One can use @Id on each of the columns that form the primary key and @GeneratedValue and @SequenceGenerator on the @Id column that should be generated by a sequence.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615770", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Do I have to free memory from every initialized string? // loads a file into memory void load_file() { char *data = "This is so data"; printf("function: %s\n", data); } Will the above code leak memory? Do I have call free(data)? Why or why not? A: It cannot leak because you did not dynamically allocate it. data is a string literal and not a dynamically allocated array of characters. A: You don't allocate any memory there, so no memory is getting leaked. You are simply copying a pointer to an existing string in the executable image, not the string itself. For that reason, the type of data should be const char* to prevent accidental changes to the string to which data points. data itself, a pointer, is allocated on the stack, just like i in int i = 5; would be. That kind of implicit allocation is de-allocated automatically too.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615781", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Where to put resources (css/images) in CodeIgniter? I am doing some testing with CI and have it running in a folder. http://www.example.com/sub-folder/ for instance My directory structure is like this (where / is sub-folder/): / |-/system |-/application I have eclipse as my IDE with 2 projects, 1 for system, 1 for application, where application is my project that includes a reference to system. My .htaccess file prevents access to system directory. I would like to have my images and CSS placed into: application/resources/images and application/resources/css respectively. I would like to be able to use <link rel="stylesheet" href="/sub-folder/css/style.css" /> However, after spending some time testing and searching, I haven't been able to get the CSS file to load from the application directory. What do I need to change or add in my .htaccess to be able to do this? The contents of my .htaccess follows: <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / ### Canonicalize codeigniter URLs # If your default controller is something other than # "welcome" you should probably change this RewriteRule ^(welcome(/index)?|index(\.php)?)/?$ / [L,R=301] RewriteRule ^(.*)/index/?$ $1 [L,R=301] # Removes trailing slashes (prevents SEO duplicate content issues) RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.+)/$ $1 [L,R=301] # Removes access to the system folder by users. # Additionally this will allow you to create a System.php controller, # previously this would not have been possible. # 'system' can be replaced if you have renamed your system folder. RewriteCond %{REQUEST_URI} ^system.* RewriteRule ^(.*)$ /index.php/$1 [L] # Checks to see if the user is attempting to access a valid file, # such as an image or css document, if this isn't true it sends the # request to index.php RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [L] A: Instead of <link rel="stylesheet" href="/sub-folder/css/style.css" /> You could do <link rel="stylesheet" href="<?php echo base_url('application/sub-folder/css/style.css'); ?>" /> I usually keep my assets in the root folder (where the main index.php file is) and use this asset library to load everything. If you want to keep your assets in application/sub-folder you could do this: A: I set up my CI projects like this: * *application (my application files) *assets (publicly accessible css, js and images etc) *system (codeigniter core) Typically, if I'm building in a CMS I'll put the CMS assets inside the application folder since they're basically private.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615783", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I use php to check another server's speed? Using PHP, I would like to download 50mb of a 1gb movie file to check if the upload speed of server hosting the movie goes to at least 100kB/s in that exact moment. Is that possible? A: Use curl_setopt with the CURLOPT_RANGE option.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615790", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Facebook OpenGraph - issues with Activity Plugin I've been able to post activities to my personal wall and timeline, but I don't seem to be able to get the Activity Plugin to go no matter how I call it. I get a success when I call it, and have also been getting a success code from the command line CURL calls. <script type="text/javascript"> function postAttend() { FB.api('/me/kaplangraph:attend' + '?class=http://samples.ogp.me/253928254644843','post', function(response) { if (!response || response.error) { alert('Error occured'); } else { alert('Post was successful! Action ID: ' + response.id); } }); } </script> This I know is working. I see them on my personal timeline. I can't however pull them up in the Activity Plugin. All of the following show up blank. Am I missing something? <fb:activity action="kaplangraph:attend"></fb:activity> <fb:activity actions="kaplangraph:attend"></fb:activity> <fb:activity actions="kaplangraph:attend" app_id=253477038023298></fb:activity> <fb:activity app_id=253477038023298></fb:activity> <fb:activity site_url="https://severe-winter-5145.herokuapp.com/"></fb:activity> Thanks guys, I also posted to the FB developer group ... hoping to get an answer there. I will post if I find anything, but I agree this is a bug and not a beta issue. It says in the example that this will work for devs/admins/etc ... just not the world. I am guessing somehow in the transition they killed the activity feed, as I am having trouble with others as well. A: The Facebook timeline and new open graph are still in beta. I'm pretty sure it won't show up in the activity plugin until it is out of beta. A: I think this is a bug; Yes, they are in beta, but the tutorial makes no mention of the fb:activity not working. It is also unclear what parameters should be passed (action or actions). I too have tried various ways of trying to get fb:activity to work, but for now I am waiting to see if there is any update to address this issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615791", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ReportLab Two-Column TOC? I have a PDF I am generating using ReportLab. I am using the standard TableOfContents flowable, but am trying to split it up into two columns, so it will all fit on the first page. the content will only ever be on one level, so I am not worried about odd-looking indentations. Right now I have the PageTemplate using 2 Frames to create 2 columns on the first page. I get a LayoutError: Flowable <TableOfContents at 0x.... frame=RightCol>...(200.5 x 720) too large on page 1 in frame 'RightCol'(200.5 x 708.0*) Any ideas? A: Well, color me embarrassed. For anyone else having this problem, check your DocTemplate for allowSplitting. The default is 1, but I had changed mine to 0 and that was the reason. *facepalm*
{ "language": "en", "url": "https://stackoverflow.com/questions/7615795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to merge few 3D JSON objects in JS [or jQuery] I have to merge 2 (up to 6) JSON objects. I got this code: http://jsfiddle.net/5Uz27/ But with this code, I can only merge the first level of the objects, so the deeper levels are usually overwritten. Check the output. How can I fix that? A: jQuery.extend(true, original_object, extend_with); source: http://api.jquery.com/jQuery.extend/ A: With jQuery, you can use $.extend() to do a "deep"/recursive merge of objects, by passing in true as the first argument. Here's how this might work in your example: // turn the strings into objects var pref_array = $.map(json_holder, JSON.parse); // add the deep=true argument pref_array.unshift(true); // now do a deep extend, passing the array as arguments var prefs = $.extend.apply(null, pref_array ); This might be a little obtuse (you could make it even more so, but tighter, by setting pref_array to [true].concat($.map(json_holder, JSON.parse))), but it avoids the ungainly for loop (that might be personal preference, I suppose). Working jsFiddle here: http://jsfiddle.net/e6bnU/
{ "language": "en", "url": "https://stackoverflow.com/questions/7615803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Custom filtering of parameters in rails 3 using config.filter_parameters I'm working on upgrading from Rails 2.3.11 to 3.0.10, and am having trouble converting what is in the ApplicationController's filter_parameter_logging. I want to filter both certain parameters, and also filter them if they appear in the value of something like a :referrer tag. I can get the regular parameters filtered out in my application.rb config.filter_parameters += [:password, :oauth, ...] But what I'm having trouble with is the block that we also pass in filter_parameter_logging. It also filters out the parameters in any value that looks like a url, so something like http://example.com?password=foobar&oauth=123foo&page=2 would be logged as http://example.com?password=[FILTERED]&oauth=[FILTERED]&page=2. I need a way for rails to both filter the specified params, and also filter only those params out from other values, like in the url above. Here's what it looked like in filter_parameter_logging: FILTER_WORDS = %{password oauth email ...} FILTER_WORDS_REGEX = /#{FILTER_WORDS.join("|")}/i #Captures param in $1 (would also match things like old_password, new_password), and value in $2 FILTER_WORDS_GSUB_REGEX = /((?:#{FILTER_WORDS.join("|")})[^\/?]*?)(?:=|%3D).*?(&|%26|$)/i filter_parameter_logging(*FILTER_WORDS) do |k,v| begin # Bail immediately if we can next unless v =~ FILTER_WORDS_REGEX && (v.index("=") || v.index("%3D")) #Filters out values for params that match v.gsub!(FILTER_WORDS_GSUB_REGEX) do "#{$1}=[FILTERED]#{$2}" end rescue Exception => e logger.error e end end Is there a way to make rails filter in this way using config.filter_parameters in application.rb? I can't seem to find any good documentation on how to customize filtering in rails 3. A: Figured it out. You can pass a lambda statement to config.filter_parameters, so after I add the parameters to filter, I have this now: config.filter_parameters << lambda do |k,v| begin # Bail immediately if we can next unless v =~ FILTER_WORDS_REGEX && (v.index("=") || v.index("%3D")) #Filters out values for params that match v.gsub!(FILTER_WORDS_GSUB_REGEX) do "#{$1}=[FILTERED]#{$2}" end rescue Exception => e logger.error e end end
{ "language": "en", "url": "https://stackoverflow.com/questions/7615805", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: renamed heroku app from website, now it's not found After renaming my heroku app from the heroku website, whenever I cd to its directory in a terminal and run any heroku command, I get App not found. Does anybody know of a way to remedy this? A: From the Heroku docs... If you rename from the website ... [your app] will need to be updated manually: git remote rm heroku heroku git:remote -a newname A: There is another way, you can fix it by renaming the app to the original name via web. To find out the old name use heroku command line: > heroku rename newname which will spit out the old name. Use the old name to rename the app via web. You can check if renaming success by running > heroku info Once done you can rename to the preferred name by using > heroku rename preferredname A: The Answer by James Ward is also correct, alternatively try doing this: 1). open a terminal 2). Go to your_app_directory/.git/config 3). Once you open the config file then edit as follows: Change url = [email protected]:old_app_name.git to url = [email protected]:new_app_name.git Obviously substituting your apps old name to its new name. Hope it helps Also checkout this link renaming from cli - heroku A: Try to update the git remote for the app: git remote rm heroku git remote add heroku [email protected]:yourappname.git A: James Ward's solution didn't work for me. I had to enter my git url in a different format: git remote rm heroku git remote add heroku https://git.heroku.com/appname.git A: git remote rm heroku heroku git:remote -a newname
{ "language": "en", "url": "https://stackoverflow.com/questions/7615807", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "169" }
Q: Programmatically added UIImageView won't show up I've been trying for an hour and nothing I do can seem to make this show the image: UIImageView*logo=[[UIImageView alloc] initWithImage:[UIImage imageNamed: @"logo.png"]]; logo.frame=pos; // a CGRect I previously created self.taskbarlogo=logo; [logo release]; [self.popupwindow addSubview:self.taskbarlogo]; logo.png is definitely there in the project this is the last subview added to self.popupwindow so it should be on top the hidden property is never handled anywhere so it should be visible The following NSLog confirms the placement of the UIImageView's frame: NSLog(@"frame: %f %f %f %f",self.taskbarlogo.frame.origin.x,self.taskbarlogo.frame.origin.y, self.taskbarlogo.frame.size.width, self.taskbarlogo.frame.size.height); It reports: frame: 20.000000 20.000000 96.000000 33.000000 this is certainly onscreen, or certainly should be as my superview's frame is much larger than this what am I missing?! there is no crash, no errors, just.... no image. A: Check the file inspector (one of the right side tabs) under Target Membership and make sure the image belongs to all targets where the resource is desired. Also call bringSubviewToFront to be sure it's on top. A: does it happen in iDevice AND in simulator? try to delete the folder "build" in you project folder. control that your file is checked for export as resource in xcode. try menu:build:clean (and clean all target)
{ "language": "en", "url": "https://stackoverflow.com/questions/7615817", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Devexpress C# XtraGrid Single Cell Edit Issues I'm about to pull my hair out for something that is probably very simple. This is using the XtraGrid. Let's assume I have two columns and x number of rows, contained in one column is just a checkbox that I set with the columnedit property and the other is a value. I have a text box set to be the editor of this second value. How can I set this up so that if I check the checkbox for that row, it will allow editing to the number in the value field next to it? I have the allowedit set to true for the checkbox column, but if I set the allowedit to true for the 2nd column in say the checkbox checkedchanged event handler, it will allow all of the cells in that column to be edited. I have no other properties like readonly set or anything like that. How can I distinguish between a single cell in that column and activate the editor while leaving the others readonly based on that checkbox in the same row? I have a feeling it involves using ShowingEditor and CustomRowCellEdit, but I'm not sure how to set that up. Could someone take me through what I would need to do in order to accomplish this? What settings do I need to put for the readonly/allowedit properties for this column and what would I need to put in those ShowingEditor/CustomRowCellEdit methods to do this? I'm really new at this so it is probably a really basic question, but I need some help! Some code examples for C# to determine which cell is selected would help me, but I just need to figure this out. Thanks!!! A: Yes your are right, you have to manage this by implementing the ShowingEditor Event This code for demonstration porpuses: First I bond the gridview1 to a RandomClass public class RandomClass { public bool AllowEdit { get; set; } public string Text { get; set; } public randomClass() { this.AllowEdit = true; Text = "Text1"; } } then implement the ShowingEditor Event, Every time the gridview1 tries to open the editor for the second column it checks whether AllowEdit column checked or not and take action according to it private void gridView1_ShowingEditor(object sender, CancelEventArgs e) { if (gridView1.FocusedColumn.FieldName == "Text" && !IsAllowingEdit(gridView1, gridView1.FocusedRowHandle)) { e.Cancel = true; } } private bool IsAllowingEdit(DevExpress.XtraGrid.Views.Grid.GridView view,int row) { try { bool val = Convert.ToBoolean(view.GetRowCellValue(row, "AllowEdit")); return val; } catch { return false; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7615818", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Cocoa NSNotificationCenter communication between apps failed I need to communicate between two different console apps, Observer and Client. In the Observer app I added this code: [[NSNotificationCenter defaultCenter] postNotificationName:@"MyNotification" object:self]; In the Client app I added this code: [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(trackNotification:) name:@"MyNotification" object:nil]; -(void)trackNotification:(NSNotification*)notif { NSLog(@"trackNotification: %@", notif); NSLog(@"trackNotification name: %@", [notif name]); NSLog(@"trackNotification object: %@", [notif object]); NSLog(@"trackNotification userInfo: %@", [notif userInfo]); } but nothing happens. I read all the documentation, but I am brand new in Mac OS X. Any ideas? I read about the Distributed Notifications, I changed my code and now looks like this: In the server side: [[NSDistributedNotificationCenter defaultCenter] addObserver:self selector:@selector(trackNotification:) name:@"MyNotification" object:nil]; -(void)trackNotification:(NSNotification*)notif { NSLog(@"trackNotification: %@", notif); NSLog(@"trackNotification name: %@", [notif name]); NSLog(@"trackNotification object: %@", [notif object]); NSLog(@"trackNotification userInfo: %@", [notif userInfo]); } In the client side: NSMutableDictionary *info; info = [NSMutableDictionary dictionary]; [info setObject:@"foo" forKey:@"bar"]; [[NSDistributedNotificationCenter defaultCenter] postNotificationName:@"MyNotification" object:nil userInfo:info deliverImmediately:YES]; I run both applications, but nothing happens. What am I doing wrong? A: NSNotificationCenter is only for notifications within one app. You want NSDistributedNotificationCenter. You can find more details in the Notification Programming Topics. A: I solved my problem. This is the source code: In the client side: NSDictionary *user = [NSDictionary dictionaryWithObjectsAndKeys: @"John Doe", @"name", @"22222222222", @"phone", @"Dummy address", @"address", nil]; //Post the notification NSString *observedObject = @"com.test.net"; NSDistributedNotificationCenter *center = [NSDistributedNotificationCenter defaultCenter]; [center postNotificationName: @"Plugin Notification" object: observedObject userInfo: user deliverImmediately: YES]; In the server side NSString *observedObject = @"com.test.net"; NSDistributedNotificationCenter *center = [NSDistributedNotificationCenter defaultCenter]; [center addObserver: self selector: @selector(receiveNotification:) name: @"Plugin Notification" object: observedObject]; receiveNotification definition -(void)receiveNotification:(NSNotification*)notif { NSlog(@"Hello"); } In dealloc method [[NSDistributedNotificationCenter defaultCenter] removeObserver:self name: @"Plugin Notification" object: nil];
{ "language": "en", "url": "https://stackoverflow.com/questions/7615820", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can someone point me to exact details on javax.net.debug? I'd like to get exact details on the SSL debug output generated using javax.net.debug. I have looked, but nearly everything just goes through a sample file. Sorry in advance if this is easier to find then I expected. A: What do you mean by the exact details? Oracle provides a pretty good tutorial on how to debug SSL connections, but if you're trying to find the Javadoc for it, I don't think it's available. A: I don't understand what it is that you don't understand. There's the specification of the option itself in the JSSE Reference Guide. There's the tutorial mentioned by @JavaGeek. You definitely need to understand the SSL handshake process to understand the output for the handshake option, and your reference for that is RFC 2246, or th excellent book by Eric Rescoria if you like. You would need to understand the TrustManager and KeyManager interfaces to make much sense out of the keymanager and trustmanager options, and the SSLContext and friends to understand the session and context stuff.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615842", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: plot if col A has substring I need to do this in gnuplot: plot 1:4 where col 2=="P1", col 3=="3", col 1 has substring "blur1" Heres a dataset: col_1 col_2 col_3 col_4 gcc.blur1.O0 P1 3 10.5 icc.blur1.O2 P2 5 9.8 gcc.blur2.O3 P2 3 8.9 Thanks in advance. A: AFAIK you need to use an external script to check for substrings. Something like awk and use plot "< awk '{...awk commands...}' input.dat" If you just want to test col_2 for P1 you can do it in gnuplot via f(x,y)= (x eq "P1"? y : 1/0) plot "input.dat" u 3:(f(strcol(2),$4)) strcol(n) gets the n-ths column as a string. "eq" can be used to compare strings. A: Such a simple check can be done with gnuplot's strstrt function. It returns the index of the first character found, or 0 if the substring wasn't found: strstrt(strcol(3), 'blur1') > 0 So, your plot command can look like matchesLine(col1, col2, col3) = strstrt(strcol(1), col1) > 0 && strcol(2) eq col2 && strcol(3) eq col3 plot 'file' using (matchesLine("blur1", "P1", "3") ? $1 : 1/0):4 A: If you know the exact position of the substring in advance, you can try to check for equality on that portion like this: strcol(1)[5:9] eq 'blur1' ps.: Here are some handy examples for dealing with strings in gnuplot: http://gnuplot.sourceforge.net/demo/stringvar.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7615843", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Set "expires" header for a whole directory So let's say: - .htaccess * assets |> images |> logo.png |> css |> style.css |> home.css How can i set the expires header for the whole assets folder and its contents? I know that i can set it by type like: ExpiresByType text/javascript "modification plus 2 hours 45 minutes" But what about for a whole directory? A: At the .conf level, use a <directory> directive: <Directory /path/to/your/assets/folder> ExpiresDefault ... </Directory> If you have only .htaccess control, then put a .htaccess into the assets folder with the same ExpiresDefault directive
{ "language": "en", "url": "https://stackoverflow.com/questions/7615844", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Remove internal "__type" tags in ASP.NET Restful WCF I'm developing a RESTful WCF, and am currently having trouble getting nice, clean JSON-serialized return values. A little while back, I got rid of "Key" and "Value" tags around each of my keys and values (caused by serializing a Dictionary<string, object> object) by using a wrapper. But when I did that, "__type" tags started showing up. I managed to get rid of the "d" tag, along with the first "__type" tag by replacing WebScriptServiceHostFactory with WebServiceHostFactory in the ServiceHost tag of my svc file. So my result looks like this: {"Status":"Success","Data":{"__type":"SerializableDictionaryOfstringanyType:#MyNamespace.MyFolder","Key1":"Value1","Key2":"Value2","Key3":"Value3"}} But I want it to look like this: {"Status":"Success","Data":{"Key1":"Value1","Key2":"Value2","Key3":"Value3"}} My test webservice code looks like this: [OperationContract] [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] public SerializableDictionary<string, object> Test1(String Token, String Id) { DataTable testTable = new DataTable(); testTable.Columns.Add("Key1", typeof(System.String)); testTable.Columns.Add("Key2", typeof(System.String)); testTable.Columns.Add("Key3", typeof(System.String)); DataRow testRow = testTable.NewRow(); testRow["Key1"] = "Value1"; testRow["Key2"] = "Value2"; testRow["Key3"] = "Value3"; testTable.Rows.Add(testRow); return SuccessfulResult(testTable); } EDIT: And the SuccessfulResult function looks like this (sorry for forgetting it): private SerializableDictionary<string, object> SuccessfulResult(DataTable dt = null) { SerializableDictionary<string, object> result = new SerializableDictionary<string, object>(); result.Add("Status", "Success"); if (dt == null || dt.Rows.Count != 1) return result; SerializableDictionary<string, object> dct = new SerializableDictionary<string, object>(); foreach (DataColumn currCol in dt.Rows[0].Table.Columns) dct.Add(currCol.ColumnName, dt.Rows[0][currCol.ColumnName].ToString()); result.Add("Data", dct); return result; } If anybody has any ideas on how I might get rid of that last little "__type" tag, I would love to hear them! Thanks very much, and let me know if there's anything else I can post that might be helpful. A: Okay, fixed it up - but ended up doing things a little differently. WCF seems to insist on putting in those internal "__type" tags when it serializes Dictionaries, but for some reason, it doesn't do the same thing with Streams. Here's the new webservice method code (just the return type has changed): [OperationContract] [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] public Stream Test1(String Token, String StreamId) { DataTable testTable = new DataTable(); testTable.Columns.Add("Key1", typeof(System.String)); testTable.Columns.Add("Key2", typeof(System.String)); testTable.Columns.Add("Key3", typeof(System.String)); DataRow testRow = testTable.NewRow(); testRow["Key1"] = "Value1"; testRow["Key2"] = "Value2"; testRow["Key3"] = "Value3"; testTable.Rows.Add(testRow); return SuccessfulResult(testTable); } And here's the new SuccessfulResult function (which is what made the difference): private Stream SuccessfulResult(DataTable dt = null) { Dictionary<string, object> returnDict = new Dictionary<string, object>(); returnDict.Add("Status", "Success"); Dictionary<string,object> dct = new Dictionary<string,object>(); foreach (DataColumn currCol in dt.Rows[0].Table.Columns) dct.Add(currCol.ColumnName, dt.Rows[0][currCol.ColumnName].ToString()); returnDict.Add("Data", dct); string sResponse = json.Serialize(returnDict); byte[] byResponse = Encoding.UTF8.GetBytes(sResponse); return new MemoryStream(byResponse); } Now the output looks exactly how I want it to look: {"Status":"Success","Data":{"Key1":"Value1","Key2":"Value2","Key3":"Value3"}} Anyway, I hope this example helps somebody else :) A: In some case, the browser will treat response stream as binary, so, it will show download file popup. Then you should using: string result = "Hello world"; byte[] resultBytes = Encoding.UTF8.GetBytes(result); WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain"; return new MemoryStream(resultBytes); A: I know that this was a long time ago, but I found a really simple way to make that possible. In the Web.Config file you should change a line. Use <webHttp/> instead of <enableWebScript/> <endpointBehaviors> <behavior> <webHttp /> </behavior>
{ "language": "en", "url": "https://stackoverflow.com/questions/7615845", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Getting Intellisense inside <% %> tags For some reason, Intellisense has stopped working inside code blocks (<% %>) in Visual Studio 2010 in both aspx and ascx files. This was working, but I obviously flipped some setting unknowingly. Anyone run into this before? It's pretty annoying. A: Intellisense within inline code blocks is hit or miss a lot of times. I've tried to discern some logical reason for it, but there doesn't seem to be one. I've noticed that it works sometimes if you close and reopen the page, or close and reopen Visual Studio, but I don't know of any sure-fire way to ensure that it works.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615846", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using MVVM to Solve Combobox Interaction I'm new to WPF and I haven't used MVVM yet but I think I'm in a situation where it might help. In my program I've got several comboboxes that all have the same comboboxitems and when the user makes a selection in one of the comboboxes the selected comboboxitem gets disabled in the other comboboxes. (i.e. If the user has selected the comboboxitem with value 'a' in combobox #1 and selected the comboboxitem with value 'b' in combobox #2 then in remaining comboboxes both the comboboxitems with values 'a' and 'b' are disabled) Anyway, I'm having trouble doing this programmatically in the code-behind and I was hoping someone could describe how to approach this problem using MVVM. Thanks MG A: Here is one of the best primers on MVVM applied to WPF, with first rate code. It isn't a quick read, and don't get frustrated if even seemingly simple things take some time to grok. To answer your question more directly, you use MVVM to make data binding work (not to mention your logic testable). So for a ComboBox, you firstly supply it with data. probably using an ObservableCollection which has support for data binding in it. You can synchronize the Selected Item(s) in the ComboBox(es) to a property(ies) in your view model, and change the contents of one based on a change in the Selected Item. Suggest you read that article and work through some code, then follow up with some more targeted questions using code. HTH, Berryl
{ "language": "en", "url": "https://stackoverflow.com/questions/7615848", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Advance slideshow manually with jquery please be easy - first post! Looking to modify the following script: http://jonraasch.com/blog/a-simple-jquery-slideshow Love it's simplicity, trying to find a way to add an advance function Preferably on the img or div - on click or from a link. Any suggestions? Appreciate the help edit, below is the script and here is a link to a working version: link to a live testing page script: function slideSwitch() { var $active = $('#slideshow IMG.active'); if ( $active.length == 0 ) $active = $('#slideshow IMG:last'); // use this to pull the images in the order they appear in the markup var $next = $active.next().length ? $active.next() : $('#slideshow IMG:first'); // uncomment the 3 lines below to pull the images in random order // var $sibs = $active.siblings(); // var rndNum = Math.floor(Math.random() * $sibs.length ); // var $next = $( $sibs[ rndNum ] ); $active.addClass('last-active'); $next.css({opacity: 0.0}) .addClass('active') .animate({opacity: 1.0}, 1000, function() { $active.removeClass('active last-active'); }); } $(function() { setInterval( "slideSwitch()", 5000 ); }); style: #slideshow { position:relative; height:350px; } #slideshow IMG { position:absolute; top:0; left:0; z-index:8; opacity:0.0; } #slideshow IMG.active { z-index:10; opacity:1.0; } #slideshow IMG.last-active { z-index:9; } html: <div id="slideshow"> <img src="image01.jpg" width="262" height="496" border="0" class="active" /> <img src="image02.jpg" width="262" height="496" border="0" /> </div> A: That particular sample already has an advance function built in: slideSwitch. This function is called in a setInterval loop to advance the slide show. All you need to do is hook up that method to your button click and you should be good to go. HTML: <div id="advanceShow">Click to Advance</div> JavaScript $(document).ready(function() { $('#advanceShow').click(function() { slideShow(); }); }); A: We could do this by changing the interval to a timeout, which gives us an id which we can reset at will. Then we can use a click even to reset this interval and advance manually, which in turn will start up the interval again. Using the simplest example on jonraasch.com: window.slideInterval = null; function slideSwitch() { var $active = $('#slideshow IMG.active'); var $next = $active.next(); $next.addClass('active'); $active.removeClass('active'); window.slideInterval = setTimeout('slideSwitch()', 5000 ) } jQuery(function() { window.slideInterval = setTimeout('slideSwitch()', 5000 ); }); $(el).click(function(){ // reset interval clearTimeout(window.slideInterval); // trigger next slide manually slideSwitch(); }); Edit Over the weekend I had the time to put some more attention to this, and I read up on the best practices in making a jQuery plugin. Code is slightly documented, but all in all fairly standard and not very complex, though has a fair bit of juggling with variables :) If you use anything you should use this. http://jsfiddle.net/sg3s/RFJMy/214/ btw, you can just delete the prev and rand functions if you don't want to use them, start, stop, init and transit to make the whole work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615850", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Asynchronous Callback functions: Iphone Versus Android On Callback On Iphone File A: @protocol servicedelegate -(void)taskCompleted:(NSDcitionary*) dict; @end -(void) performtask callback=@"taskCompleted:"; [(id)delegate performSelector:NSSelectorFromString(callback) withObject:data]; File B: -(void) taskcompleted:(NSDictionary*)dict { //don something when File A fisnihed the taskcompleted and have the data // this callback on File B will be awaken from File A's delegate function } The question How does Android implement the above, File A waiting to getting the data, and nobody knows how long, but once finished, File B would awaken by the delegate callback function of taskcompleted. A: There are a couple different ways: * *Handlers *AsyncTask I'm a fan of AsyncTask myself, but they require more boilerplate. Handlers can often be simpler.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615852", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: BizTalk: Finding the document specification failed Good afternoon all, I've got an issue with a BizTalk orchestration that's really odd. The first receive shape of my orchestration fails with the following message: There was a failure executing the receive pipeline: "Microsoft.BizTalk.DefaultPipelines.XMLReceive, Microsoft.BizTalk.DefaultPipelines Source: "XML disassembler" Receive Port: "ReceiveCanonicalPort" Reason: Finding the document specification by message type "http://www.openapplications.org/oagis/9#ProcessInvoice" failed. Verify the schema deployed properly. I put together a test document with the first few lines like this: <?xml version="1.0" encoding="utf-8"?> <ProcessInvoice xmlns="http://www.openapplications.org/oagis/9" releaseID="9.0" targetNamespace="http://www.openapplications.org/oagis/9" > What I've checked already: I've checked the schema: The target namespace is 'http://www.openapplications.org/oagis/9' The root node is 'ProcessInvoice' The schema validates. My input file validates against the schema. I've checked the schema is deployed. I've looked to see if there is another schema with a duplicate namespace and root node. I've restarted the host instances and redeployed several times. I tried setting the xml disassembler 'allow unrecognized message' property to true. This results in an object not set to an instance exception instead. Which would seem to indicate that it's not de-serializing it. I've prayed to the great god Boogie. Any other ideas? Thanks A: You must have another version of that schema defined somewhere in another assembly. Are you sure you have checked every possible application (include BizTalk Application 1)? The only other thing I can think of is maybe you have an assembly redirect in the config file which is redirecting to a version which does not exist, however I am not certain you would even get your observed behavior if this was the case. Another thing - maybe an older version of the schema is GAC'd and a host instance still has hold of it. Try rebooting to ensure. Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615853", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Using a HorizontalScrollView with ImageView's over Gallery LazyLoad? Okay I have an idea and I want to know what you all think. So for my project I have an gallery. I want to load images into the gallery using Lazyloading But lazyloading doesnt seem to work to well with Gallery. It seems it works better with just having a imageview. I just cant figure out how to get it to work correctly with Gallery. I was wondering if I had a horizontalscrollview with many images I need to do this work Can it be efficient? A: What's wrong with just using a simple adapter? public class MyActivity extends Activity { @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); Gallery gallery = new Gallery(this); gallery.setAdapter(new MyApater()); setContentView(gallery); } private class MyAdapter extends BaseAdapter { /** Make sure your list gets populated somehow. */ List<Integer> mContent = new ArrayList<Integer>() { mContent.add(R.drawable.d1); mContent.add(R.drawable.d2); ... }; @Override public int getCount() { return mContent.size(); } @Override public Object getItem(int position pos) { return mContent.get(pos); } @Override public long getItemId(int pos) { return pos; } @Override public View getView(int postition, View view ViewGroup vg) { /** Inflate your view here. (using the resource id's of mContent) */ return (ImageView)findViewById(mContent.get(pos)); } } } EDIT: Sory if I missed the point, I'm not familier with the term 'lazy loading'. A: Look here: SO This is part of one of my Galleries that is feed with LazyLoadinng. I use a DrawableCache to hold the images that I load from the web. It's working perfect.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615855", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I am having a z-index issue I have a slogan that should float above an image if the screen width is set to very wide. I've adjusted the z-index in countless ways, but can't figure out exactly how to it. The site is here: http://www.i-exercisebikereviews.com/?62/exercise-bike-reviews-schwinn the CSS is here: http://i-treadmillreviews.com/css/style.cfm Specifically, the #Slogan is the words: Home Exercise Bike Reviews - Top Picks - Sales - Coupons The #Human is the ultra hot chick on the exercise bike: How to I make the the slogan rise above the human (instead of behind the human) when the browser is very wide? A: The problem is that you have the z-index property of your #Under div set to 0. Remove that, and you're fine. See also: can I override z-index inheritance from parent element? A: Removing entirely the z-index on #Under fixes it: #Under { margin: 0px; width: 100%; height: 61px; position: relative; top: 0px; left: 0px; /*z-index: 0;*/ overflow: visible; background: url("background2.png") top left repeat-x; background: url("background2.png") top left repeat-x, -moz-linear-gradient(top, rgb(240,240,240), rgb(256,256,56)); background: url("background2.png") top left repeat-x, -webkit-gradient(linear, 0 0, 0 100%, from(rgb(240,240,240)), to(rgb(256,256,56))); background: url("background2.png") top left repeat-x, -o-linear-gradient(top, rgb(240,240,240), rgb(256,256,56)); } Style.cfm line 40
{ "language": "en", "url": "https://stackoverflow.com/questions/7615857", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JPA: @JoinTable - Both columns are Primary Keys.. How do I stop that? This is my annotation I use to generate my Join Table. @OneToMany(cascade = CascadeType.ALL) @JoinTable(name = "service_operations", joinColumns = { @JoinColumn(name = "serviceId") }, inverseJoinColumns = { @JoinColumn(name = "operationId") }) public Set<Operation> getOperations() { return operations; } Considering this is a OneToMany association, my natural assumption is that this table would generate a [ Primary Key | Foreign Key ] table, however everytime I drop and re create the database it is not the case: mysql> describe workflow_services; +-------------+------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------------+------------+------+-----+---------+-------+ | workflow_id | bigint(20) | NO | PRI | NULL | | | service_id | bigint(20) | NO | PRI | NULL | | +-------------+------------+------+-----+---------+-------+ 2 rows in set (0.00 sec) Im a tad baffled by this. Any suggestions? A: I fixed my problem by adding the following changes: I changed my @OneToMany to a @ManyToMany annotation @ManyToMany(cascade = CascadeType.ALL) @JoinTable(name = "workflow_services", joinColumns = @JoinColumn(name = "workflow_id"), inverseJoinColumns = @JoinColumn(name = "service_id")) public Set<Service> getServices() { return services; } I added a Set workflows; association in my Service object @ManyToMany(mappedBy="services") // map info is in person class public Set<Workflow> getWorkflows() { return workflows; } A: This looks correct to me. Each row in the join table should identify a pair of workflow/service items. So (workflow_id, service_id) should be the primary key. Also workflow_id should be a foreign key into the workflow table and service_id should be a foreign key into the service table. Also note that a one-to-many association between A and B does not mean that an instance of A can have the same instance of B multiple times, rather an instance of A can have multiple distinct instances of B. For example a blog Post entity can have a one-to-many association with a Tag entity. This means that a blog Post P1 can have multiple tags Java, JPA, JavaEE, but can not have the same tag multiple times.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615859", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Picking the right data structure I'm trying to teach myself java. I'm trying to write a program that takes a string with no spaces and separates it into words. My plan of attack was to partition the dictionary based on word length, then walk through the string finding possible variations. I ran into a problem with making my dictionary. I've read up on the various collections, and I thought that an array (of length 20 or so) holding HashSets would work best for me, but I can't figure out how to declare it. I think an array would be good because the index would represent the length, then a HashSet would be good because I could store the words as keys for fast look ups. This is something that I could do in seconds in the scripting languages I'm most comfortable with, but I've spent about 5 hours reading up and trying to figure it out in Java. Historically speaking, this is evidence that I'm doing something fundamentally wrong. Can someone with more java acumen help get me going? A: I don't see why you'd need an array of hashsets. Here's what I invision: Set<String> dictionary = new HashSet<String>(); dictionary.add("One"); dictionary.add("Two"); dictionary.add("Three"); dictionary.add("Four"); And here is how I would use it. Note: don't read below unless you want an actual answer to the breaking-into-words problem. It may diminish how much learning you get. So only read it if you're okay with it being spoiled. List<String> split(String sentence) { List<String> words = new LinkedList<String>(); String word = ""; // StringBuilder actually is not orders faster in // this case or I would advocate using it... for(int i = 0; i < sentence.length(); i++) { word += sentence.charAt(i); // creates a new String anyway, so StringBuilder // is far less powerful if(dictionary.contains(word) { words.add(word); word = ""; } } return words; } Some concerns: Let us assume your sentences and words are all in lowercase, to avoid case sensitivity. Let us also assume your dictionary contains every common English word. dictionary.add("this"); dictionary.add("is"); dictionary.add("a"); dictionary.add("test"); And run "thisisatest" and it will split it properly. Now, keep in mind there are other words. dictionary.add("i"); dictionary.add("sat"); dictionary.add("est"); These are all valid words. Running it will give you "this" "i" "sat" "est" In fact, by this logic, EVERY word that starts with i or a will end up getting missed. And that's bad. Especially for words like "apple" You will get a as the first word, then continue searching for "pple" and words that start with "pple". That's going to cause a lot of problems! Even if you can get around this problem, you're going to run into problems where the words are always valid. Consider "thetreescare". Is it "the" "tree" "scare" or "the" "trees" "care". You are unable to make the differentiation - ever! So the problem you have picked is a dousie, for sure! A: If your only question is the syntax, then to create an array of 20 HashSets, the syntax would be: HashSet[] mySets = new HashSet[20]; A: You probably want something like: HashSet[] dictionary = new HashSet[20]; // Initialize all sets. for (int i=0; i<dictionary.length; i++) { dictionary[i] = new HashSet<String>(); } for (String word: words) // words is array or list with all possible words { dictionary[word.length()].add(word); } A: HashSet<String>[] mySets = new HashSet[20];
{ "language": "en", "url": "https://stackoverflow.com/questions/7615864", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CSS children Selector Lets say I have the following HTML <div id="div1"> .... <span class="innercontents">...</span> .... </div> Can I select just the child of the parent ID? Could I do something like #div1 span { ... } Thanks for any help. Sorry for any confusion. I should have been more clear. In the above example I would like to just select the tags that fall under that specific A: Yes. #div1 > .innercontents. This is the immediate descendent selector, or child selector. This is the best reference for CSS selectors: http://www.w3.org/TR/css3-selectors/#selectors A: #div1 > .innercontents /* child selector */ The above will select these ids from the following HTML: c and d <div id="div1"> <div id="a"> <span id="b" class="innercontents"></span> </div> <span id="c" class="innercontents"></span> <span id="d" class="innercontents"></span> </div> if you want all descendents selected such as b, c, and d from the above HTML then use #div1 .innercontents
{ "language": "en", "url": "https://stackoverflow.com/questions/7615866", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Archiving Xcode Project for Submission When trying to archive an Xcode project for submission when setting Archive Build configuration to release, even when Reveal Archive in Organizer is checked, the Archive does not get created in the Organizer. I get the message, build succeeded though. Anybody knows what could be the reason(s)? A: Apparently, I missed some steps when I created the Distribution Provisioning Profile. After creating Distribution Provisioning Profile correctly, everything started to act as I wished.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615874", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: replacing escape character with double qoutes in c# I have the following string in a variable called, s: [{\"roleIndex\":0,\"roleID\":\"c1_r0_23\",\"roleName\":\"Chief Executive\"}, {\"roleIndex\":1,\"roleID\":\"c1_r1_154\",\"roleName\":\"Chief Operator\"}] and I'm trying to replace \" with " with the following command: s.ToString().Replace("\"", """"); but this is not working. What is the correct syntax in c#? A: Try s.ToString().Replace(@"\""", "\""). The @ tells C# to interpret the string literally and not treat \ as an escape character. "\"" as the second argument uses \ as an escape character to escape the double quotes. You also don't need to call ToString() if s is already of type string. Last but not least, don't forget that string replacement is not done in place and will create a new string. If you want to preserve the value, you need to assign it to a variable: var newString = s.ToString().Replace(@"\""", "\""); // or s = s.Replace(@"\""", "\""); if "s" is already a string. A: Update if you have a string containing ", when you view this string in the Visual Studio immediate window it will display it as \". That does not mean that your string contains a backslash! To prove this to yourself, use Console.WriteLine to display the actual value of the string in a console, and you will see that the backslash is not there. Here's a screenshot showing the backslash in the immediate window when the string contains only a single quote. Original answer Three things: * *Strings are immutable. Replace doesn't mutate the string - it returns a new string. *Do you want to replace a quote "\"" or a backslash followed by a quote "\\\"". If you want the latter, it would be better to use a verbatim string literal so that you can write @"\""" instead. *You don't need to call ToString on a string. Try this: s = s.Replace(@"\""", "\""); See it on ideone. A: Ironically, you need to escape your quote marks and your backslash like so: s.ToString().Replace("\\\"", "\""); Otherwise it will cat your strings together and do the same as this (if you could actually use single quotes like this): s.ToString().Replace('"', ""); (your second string has four quotes... that's why you're not getting a compile error from having """)
{ "language": "en", "url": "https://stackoverflow.com/questions/7615878", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Tomcat usurping 404 not found error, returns 500 instead ObHumor: Apparently my "not found" page cannot be found. :-) I have a Wicket app that has a custom 404 Not Found page. Used to work fine when we ran under Glassfish, and it continues to work fine when I use Jetty and Start.java. But when running under Tomcat 7.0.19 the app never shows its 404 page- Tomcat seems to "eat" the bad request, and returns a 500 to the client. I see the following in the logs: 0:0:0:0:0:0:0:1%0 - - [30/Sep/2011:16:35:57 -0400] "GET /bad-link HTTP/1.1" 500 5 I have the following in my web.xml: <error-page> <error-code>404</error-code> <location>/404</location> </error-page> And indeed if I visit that page directly (/404), I see my 404 page. But if I request "/bad-link", I get Tomcat's 500 response. Here is my tomcat server.xml: <?xml version='1.0' encoding='utf-8'?> <Server port="8005" shutdown="SHUTDOWN"> <!-- Security listener. Documentation at /docs/config/listeners.html <Listener className="org.apache.catalina.security.SecurityListener" /> --> <!--APR library loader. Documentation at /docs/apr.html --> <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" /> <!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html --> <Listener className="org.apache.catalina.core.JasperListener" /> <!-- Prevent memory leaks due to use of particular java/javax APIs--> <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" /> <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" /> <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" /> <GlobalNamingResources> <!-- Editable user database that can also be used by UserDatabaseRealm to authenticate users --> <Resource name="UserDatabase" auth="Container" type="org.apache.catalina.UserDatabase" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" pathname="conf/tomcat-users.xml" /> </GlobalNamingResources> <Service name="Catalina"> <!--The connectors can use a shared executor, you can define one or more named thread pools--> <!-- <Executor name="tomcatThreadPool" namePrefix="catalina-exec-" maxThreads="150" minSpareThreads="4"/> --> <!-- A "Connector" represents an endpoint by which requests are received and responses are returned. Documentation at : Java HTTP Connector: /docs/config/http.html (blocking & non-blocking) Java AJP Connector: /docs/config/ajp.html APR (HTTP/AJP) Connector: /docs/apr.html Define a non-SSL HTTP/1.1 Connector on port 8080 --> <Connector port="8080" protocol="HTTP/1.1" URIEncoding="UTF-8" connectionTimeout="20000" redirectPort="8443"/> <!-- A "Connector" using the shared thread pool--> <!-- <Connector executor="tomcatThreadPool" port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" /> --> <!-- Define a SSL HTTP/1.1 Connector on port 8443 This connector uses the JSSE configuration, when using APR, the connector should be using the OpenSSL style configuration described in the APR documentation --> <!-- <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true" maxThreads="150" scheme="https" secure="true" clientAuth="false" sslProtocol="TLS" /> --> <!-- Define an AJP 1.3 Connector on port 8009 --> <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" URIEncoding="UTF-8"/> <!-- An Engine represents the entry point (within Catalina) that processes every request. The Engine implementation for Tomcat stand alone analyzes the HTTP headers included with the request, and passes them on to the appropriate Host (virtual host). Documentation at /docs/config/engine.html --> <!-- You should set jvmRoute to support load-balancing via AJP ie : <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1"> --> <Engine name="Catalina" defaultHost="localhost"> <!--For clustering, please take a look at documentation at: /docs/cluster-howto.html (simple how to) /docs/config/cluster.html (reference documentation) --> <!-- <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/> --> <!-- Use the LockOutRealm to prevent attempts to guess user passwords via a brute-force attack --> <Realm className="org.apache.catalina.realm.LockOutRealm"> <!-- This Realm uses the UserDatabase configured in the global JNDI resources under the key "UserDatabase". Any edits that are performed against this UserDatabase are immediately available for use by the Realm. --> <Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/> </Realm> <Host name="localhost" appBase="webapps" unpackWARs="true" autoDeploy="true"> <!-- SingleSignOn valve, share authentication between web applications Documentation at: /docs/config/valve.html --> <!-- <Valve className="org.apache.catalina.authenticator.SingleSignOn" /> --> <!-- Access log processes all example. Documentation at: /docs/config/valve.html Note: The pattern used is equivalent to using pattern="common" --> <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" prefix="localhost_access_log." suffix=".txt" pattern="%h %l %u %t &quot;%r&quot; %s %b" resolveHosts="false"/> </Host> </Engine> </Service> </Server> My catalina.properties is vanilla except for the following line which I have added: org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH=true This allows %2F encoded slashes to appear in the URLs. Edit: in case it matters: my app is mounted at the root context (i.e. deployed as ROOT.war). A: Have you added this to your web.xml also? <filter-mapping> <filter-name>wicket.filter.my</filter-name> <url-pattern>/*</url-pattern> <dispatcher>REQUEST</dispatcher> <dispatcher>ERROR</dispatcher> </filter-mapping>
{ "language": "en", "url": "https://stackoverflow.com/questions/7615882", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Do not remove characters from path name C# I have a Windows Form Application that takes a command line argument as well. You can run the program by itself it has a GUI but when you run it in CLI it seems like C# removes some characters from my argument that I feed it. This is how it works: RemoveHTML.exe http://illen/configtc.aspx?IP=192.168.0.15&m=c The app loads but crashes because C# removed the last part of the the URL! So what it's really seeing is RemoveHTML.exe http://illen/configtc.aspx?IP=192.168.0.15 It removes the "&m=c" part and in my CLI I get this error: C:\Users\admin\Documents\Visual Studio 2010\Projects\RemoveHTML\RemoveHTML\bin\Debug>RemoveHTML.exe http://illen/configtc.aspx?IP=192.168.0.15 'm' is not recognized as an internal or external command,operable program or batch file. My code is located in the Form1_Load section and it is: string MyURL; string[] WebURL; ...... private void Form1_Load(object sender, EventArgs e) { string[] args = Environment.GetCommandLineArgs(); foreach (string arg in args) { WebURL[0] = args[1]; //WebURL[0] += "&m=c"; //WebURL[0] += (WebURL[0] + "&m=c"); //WebURL = args[1]; //MessageBox.Show(WebURL); runtimeButton_Click(sender, e); } } I am trying to find a way to not have C# remove the illegal characters, any ideas? A: When calling your application, put the URL in quotes. RemoveHTML.exe "http://illen/configtc.aspx?IP=192.168.0.15&m=c" Its not a limitation of .NET or C#. Its the way the command parser works.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615883", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Regex-ing text in a textfield to be safe for URLs being loaded You can demo this searching for the tag Black & White at http://syndex.me The logo of the site is a search field. If I search for "USA" it ajax loads all posts tagged "USA". However it does not work for "Black & White". How can one check the value of the input field for potential non alphabetic characters and things like spaces, and then change it too a safe term, i.e. Black_%26_White ? I know a little code but this kinda stuff is beyond me. I'm sure this question would be useful for other noobs. Thanks! <html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> <script type="text/javascript"> jQuery(function($) { $('#syndex').keydown(function(event) { if (event.keyCode == '13') { var syndex = $('input:text').val(); $('body').load("http://syndex.me/tagged/"+ syndex,function(){ $('input:text').val(syndex); }); } }); }); </script> </head> <body> <div id="logo"> <input id="syndex" type="text"/> </div> </body> </html> A: Do you want to strip everything except letters and numbers? var syndex = $('input:text').val().replace(/\W\D/g, ''); Or do you want to convert special characters to a URI-friendly format? $('body').load("http://syndex.me/tagged/"+ encodeURIComponent(syndex),function(){
{ "language": "en", "url": "https://stackoverflow.com/questions/7615896", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to extract an Apache FOP created PDF in C#? I have a problem in my c# project. I want to extract Apache FOP generated PDF files programatically without any 3rd party application. I tried to use many libary like PDFBox, IKVM, PDF2Text, ITextSharp, PDFSharp to extract PDF files, but failed. When i extract a FOP generated PDF to a text file, i get a lots of square symbols and other entangled characters. My question is, how can i extract a FOP generated PDF file in C#? Is there any library (written to C#), which can do that? Thanks. A: Fonts using Identity-H encoding use directly the glyph indexes for displaying the text on the page. These fonts require a ToUnicode entry in the font dictionary (in the PDF file) in order to support text extraction, otherwise it is not possible. Check the Apache FOP to see if it has a setting for including a ToUnicode entry in the font dictionary or for making the font extraction friendly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615903", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to scale UDP read throughput? Setup: Two linux (CentOS 6) servers connected back-to-back over a dedicated GigE link. Each server with 24 cores and 32GB RAM Client: Simulator shooting UDP packets as fast as it could in one thread. Each packet size is 256 bytes. I see that the maximum throughput is ~200,000 packets/sec. Server: Receive packets on the UDP socket in one thread and perform light-weight parsing. I see that the maximum throughput is ~200,000 packets/sec, with CPU one 1 core about at 85% utilization during processing. There is no packet loss, the receive buffer is set to 128M just in case. Now I have 23 additional cores i would like to use, but as soon as i add one more thread for receiving data on the server side and a client thread for sending data on the client side over a dedicated socket, I see a lot of packet loss on the server side. The server threads are completely independent of each other and do not block except for I/O. They are not contending on the socket either as each one of them sucks packets off of their own UDP sockets. I see the following behavior: * *The CPU is about 85% on each core and a process called ksoftirqd/xx using about 90% if an additional core. *I am loosing packets, the throughout drops down on each thread to about 120,000 packets/sec Google says that ksoftirqd uses CPU to handle soft interrupts and heavy system calls (UDP read) can be one of the reason for high CPU usage for this kernel thread. I repeated the experiment by pinning my process to a bunch of cores on the same physical socket and I see that the performance improved to 150,000 packets/sec with still some considerable packet loss. Is there a way i can improve the scalability of my program and minimize packet loss? A: First off, at 200,000 packets per second with 256 (data?) bytes per packet, once you consider UDP, IP, and Ethernet overhead, you're running at nearly half the capacity, counting bandwidth alone, of your gigabit link. At the packet-per-second rates you're pushing, many switches (for example) would fall over. Second, you're probably being killed by IRQs. Better network cards have tunables to let you trade off fewer IRQs for increased latency (they only interrupt once every N packets). Make sure you have that enabled. (One place to check is the module parameters for your ethernet card.) A: You can set the kernel receive buffer, but be aware that it won't help if the IRQs eat all your CPU. int n = 1024 * 512; //experiment with it if (setsockopt(socket, SOL_SOCKET, SO_RCVBUF, &n, sizeof(n)) == -1) { //oops... check this } You should also set the maximum receive buffer to a large value so the kernel doesn't limit your setting: sysctl -w net.core.rmem_max=<value> A: If your application requires 200,000 packets per second, either your protocol is not well designed, or you're doing something else wrong. Where do the 200k packets come from? Different hosts across the internet? Maybe you should load-balance it or something? As derobert pointed out, 200k packets per second represents a lot of bandwidth which will be very costly on the internet, you should probably consider a protocol redesign.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615912", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Aggregate R sum I'm writting my first program in R and as a newbie I'm having some troubles, hope you can help me. I've got a data frame like this: > v1<-c(1,1,2,3,3,3,4) > v2<-c(13,5,15,1,2,7,4) > v3<-c(0,3,6,13,8,23,5) > v4<-c(26,25,11,2,8,1,0) > datos<-data.frame(v1,v2,v3,v4) > names(datos)<-c("Position","a1","a2","a3") > datos posicion a1 a2 a3 1 1 13 0 26 2 1 5 3 25 3 2 15 6 11 4 3 1 13 2 5 3 2 8 8 6 3 7 23 1 7 4 4 5 0 What I need is to sum the data in a1, a2 and a3 (in my real case from a1 to a51) grouped by Position. I'm trying with the function aggregate() but it only works for means, not for sums and I don't know why. Thanks in advance A: This is fairly straightforward with the plyr library. library("plyr") ddply(datos, .(Position), colwise(sum)) If you have additional non-numeric columns that shouldn't be averaged, you can use ddply(datos, .(Position), numcolwise(sum)) A: You need to tell the aggregate function to use sum, as the default is for it to get the mean of each category. For example: aggregate(datos[,c("a1","a2","a3")], by=list(datos$Position), "sum") A: ag_df <-- aggregate(.~Position,data=datos,sum) should give you a data frame containing the sums of the "a" values for each of the positions. The trick here is the . in the formula represents a list of all the "non-grouping" variables in the formula. Note that you can get much the same result with: sumdf <- rowsum(datos,datos$Position,na.rm=T) Except that includes the sums of the positions as well! If you DON'T want all non-group columns aggregated, you can use cbind as in: sumdf1 <- aggregate(cbind(a1,a3)~datos$Position,datos,sum) That sums only the a1 and a3 columns.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615922", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: ClearCase: Is it a bug or a feature? When I run the following code intereactively from bash it works fine. cleartool setview $myview cleartool lsbl But when I put them in a script and try to run the script, it never returns from the first cleartool command. It seems in the interactive case the first cleartool command opens a new bash to run in and when you run the second command from the new shell it works fine. But in case of the script the new shell is not being visible and hence it seems not to return from the command. Is there anyway to keep the cleartool commands in the same bash shell they are running from? A: The cleartool setview command opens a new interactive shell. In that shell you execute the second command when you type it by hand. When you put both lines into a script, the setview executes the shell waiting for your input. The second command is executed as soon as you exit that shell. Of course the second command is not executed in the context of $myview. To make things a little bit clearer do the following: In a shell execute cleartool setview $myview five times. Type echo $$ after each setview. This gives you the process ID of the current shell. The numbers will increase. Then type exit in each shell. Do echo $$ again after each exit. The old number will appear in decreasing order. After six exits you terminal should be closed. That was the explanation. A solution for your problem might be the -exec option of the setview command: cleartool setview $myview -exec "cleartool lsbl" should do the trick. A: While it doesn't directly answer the question, the following might do what you want. It makes the second command run in the subshell that the first command opens. cleartool setview $myview << EOF cleartool lsbl EOF
{ "language": "en", "url": "https://stackoverflow.com/questions/7615923", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: When sending one email, the log shows the email twice? Though it's sending only once? in my app, DJ fires off a an email but for some reason I see the email in the log file twice though it is sent only once? I confirmed in the logs that DJ runs only once and user_mailer runs only once. So why do I see the email twice in the log file? What is Rails doing? Rendered user_mailer/room_notification.text.erb (0.9ms) Sent mail to [email protected] (1097ms) Date: Fri, 30 Sep 2011 13:34:56 -0700 From: "roomxcom" <no-reply@roomxcom> To: [email protected] Message-ID: <[email protected]> Subject: [Email Testing] Test 12 Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 7bit AAAAA Did something: Test 12 http://localhost:3000/c19 Sent mail to [email protected] (3510ms) Date: Fri, 30 Sep 2011 13:34:56 -0700 From: "roomxcom" <no-reply@roomxcom> To: [email protected] Message-ID: <[email protected]> Subject: [Email Testing] Test 12 Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 7bit AAAAA Did something: Test 12 http://localhost:3000/c19 SQL (0.1ms) BEGIN AREL (0.3ms) DELETE FROM "delayed_jobs" WHERE "delayed_jobs"."id" = 25 SQL (0.4ms) COMMIT Delayed Job: UserMailer.delay.room_notification(room, record.user, room_member.user, record.item) User Mailer: def room_notification(room, user_creator, user_recipient, item) ... mail( :from => "XXXX <[email protected]>", :to => user_recipient.email, :subject => "[#{@room.title}] #{@item.title}" ).deliver Any idea what' going on and why rails is showing the email in the log twice? Thanks A: edit: Here's a clearer explanation now that it's daytime and I've had some coffee... This line is adding the message to the queue: UserMailer.delay.room_notification(room, record.user, room_member.user, record.item) So Delayed_job then calls the room_notification method in UserMailer to send the mail: def room_notification(room, user_creator, user_recipient, item) # ... mail(:from => "XXXX <[email protected]>", :to => user_recipient.email, :subject => "[#{@room.title}] #{@item.title}" ).deliver end This would be enough in itself to send the mail but you also have a redundant .deliver on the end of the mail method so it's sending it twice. TL;DR Remove .deliver from mail(...) in the room_notification method and everything should be fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615927", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there anyway to add a loading message to rich:dataTable? Has anyone found a way of display a loading message while rich:dataTable loads? I've found that if the load operations backing DataModel takes along time it results in the request taking along time. Is the an effective way of display a message to the user during this load? I'm using Richfaces 3.3.3. A: You can use a4j:status. Refer to Exadel livedemo for more details: http://livedemo.exadel.com/richfaces-demo/richfaces/status.jsf?c=status&tab=usage If you need to show messages on data table interactions only, you can limit area for a4j:status by a4j:region: <a4j:region> <a4j:status startText="Loading. Please wait..." > <rich:dataTable .../> </a4j:region> UPDATE: For lazy loading of some content, the following approach can be used. Create a facelet (or component): <ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:c="http://java.sun.com/jstl/core" xmlns:a4j="http://richfaces.org/a4j" xmlns:rich="http://richfaces.org/rich"> <h:panelGroup id="lazyP#{id}" layout="block"> <ui:fragment rendered="#{lazy.isRendered(id)}"> <ui:insert name="lazy"/> </ui:fragment> <ui:fragment rendered="#{not lazy.isRendered(id)}"> <h:outputText value="Loading..."/> <a4j:region> <a4j:jsFunction name="loadData#{id}" reRender="lazyP#{id}" action="#{lazy.release(id)}" limitToList="true" ajaxSingle="true" eventsQueue="lazyQueue"/> </a4j:region> <script type="text/javascript"> jQuery(document).ready(function() { loadData#{id}(); }); </script> </ui:fragment> </h:panelGroup> lazy is reference of bean (I use page scope) which stores map of what was rendered and what was not (release method marks item as rendered). Then you can use that like the following: <ui:decorate template="lazyLoad.xhtml"> <ui:param name="id" value="someId"/> <ui:define name="lazy"> <rich:dataTable ... /> </ui:define> </ui:decorate>
{ "language": "en", "url": "https://stackoverflow.com/questions/7615931", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Remove Comma From End Of String Advanced I have read plenty of ways of removing the comma at the end of a string when doing basic queries but none of the basic stuff seems to be working with this particular script. Hopefully I'm just over thinking this. My script goes through the database and places the cities under the proper states but I need the last cities comma to be removed. Here is the script I am using <?php $sql = "SELECT * FROM markets WHERE id = 0 ORDER BY market_state"; $res = mysql_query($sql); $list = array(); while ($r = mysql_fetch_object($res)) { $list[$r->market_state][$r->id]['market_cities'] = $r->market_cities; } foreach ($list as $market_state => $market_cities) { echo '<h1>' . $market_state . '</h1>'; foreach ($market_cities as $cityId => $cityInfo) { echo $cityInfo['market_cities']. ','; // etc } } ?> A: Another alternative that works really well in this situation, is to make a string and simply trim off the last comma. foreach ($market_cities as $cityId => $cityInfo) { $citystr .= $cityInfo['market_cities']. ','; } echo rtrim($citystr, ','); A: I think the cleanest way is to do this... $data = array_map(function($item) { return $item['market_cities']; }, $market_cities); $output = implode(',', $data); A: You could also use the join function to output a comma-separated list from an array. So instead of: foreach ($market_cities as $cityId => $cityInfo) { echo $cityInfo['market_cities']. ','; ... ... } It would look something like: $cities = join(",", $market_cities); echo $cities; A: You can also let mysql make the work if you don't need this "cityId": <?php $sql = "SELECT market_state,GROUP_CONCAT(market_cities) as market_cities FROM markets WHERE id = 0 GROUP BY market_state ORDER BY market_state"; $res = mysql_query($sql); $list = array(); while ($r = mysql_fetch_object($res)) { $list[$r->market_state] = $r->market_cities; } foreach ($list as $market_state => $market_cities) { echo '<h1>' . $market_state . '</h1>'; echo $market_cities; } A: echo $cityInfo['market_cities']; if(count($market_cities)<$i) { echo ","; } The simplest way of doing it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615932", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Calling a method using the string/variable of the method name inRuby Possible Duplicate: How to turn a string into a method call? Currently I have a code that is doing something like this def execute case @command when "sing" sing() when "ping" user_defined_ping() when "--help|-h|help" get_usage() end I find the case pretty useless and huge and I had like to call the appropriate method just by using the variable @command. Something like: def execute @command() end Offcourse I would not need and extra execute() method in this case. Any suggestions on how I can acheive this ruby ? Thanks! Edit: Added other method type for multiple strings. Not sure if that can also be handled in an elegant manner. A: Check out send send(@command) if respond_to?(@command) The respond_to? ensures that self responds to this method before attempting to execute it For the updated get_usage() part I would use something similar to this: def execute case @command when '--help', '-h', 'help' get_usage() # more possibilities else if respond_to?(@command) send(@command) else puts "Unknown command ..." end end end A: You are looking for send probably. Take a look at this: http://ruby-doc.org/core/classes/Object.html#M000999 def execute send @command end
{ "language": "en", "url": "https://stackoverflow.com/questions/7615943", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Parsing date and checking how recent it is in Bash I'm working on a Bash script (using Cygwin) that uses cURL to scrape a web page and check a certain date value. My cURL and grep calls result in the following line: <span style="float:right">Last Update: 9/30/2011 3:16:31 AM</span><p> What I need to do with the date is check if it is within the last n days. What is the best way to approach this, and how should I parse the date? A: Something like: DATESTRING="$(sed -e 's/.*Last Update: \([^<]*\)<.*/\1/' $MYINPUT)" UPDATE=$(date -d "$DATESTRING" +%s) EPOCH=$(date -d "-$n days" +%s) test "$UPDATE" -ge "$EPOCH" && echo "It's new!" A: The 'date' program should be able to parse that date format. For example: % date -d '9/30/2011 3:16:31 AM' Fri Sep 30 03:16:31 PDT 2011 So, you can use 'date' to convert that to something usable in bash (an integer, seconds since the epoch): parseddate=$(something that extracts just the date from the line ...) date -d "$parseddate" +%s Then compare that to the result of date -d '3 days ago' +%s A: I would say that the absolute best way is to parse it with another language, for example Perl, since it will be easier to parse out the date. If you'd rather stick with Bash, check the --date option in man date.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615952", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I check if a hex color in an NSString is light or dark in Objective C? I have found answers to this question that explain how to convert an NSString hex into a UIColor (I have done this) and others explaining how to convert RGB to HSB, and others explaining how to determine lightness and darkness of RGB, but I'm wondering if there is a more direct way of figuring this out that does not involve going hex->UIColor->rgb->hsb->b. Hex->hsb, for instance? Or hex->rgb->brightness calculation? I've got backgrounds that change color each time the view loads (hex values from XML), and I need to have the text on top change to white or black accordingly so it'll stay legible. Help would be much appreciated, I've been kicking this around for days now. A: See Formula to determine brightness of RGB color. Hex colors are usually RRGGBB or RRGGBBAA (alpha). how to convert hexadecimal to RGB To get three ints instead of a UIColor, you can modify the answer from that to: void rgb_from_hex(char *hexstring, int *red, int *green, int *blue) { // convert everything after the # into a number long x = strtol(hexstring+1, NULL, 16); // extract the bytes *blue = x & 0xFF; *green = (x >> 8) & 0xFF; *red = (x >> 16) & 0xFF; } // The above function is used like this: int main (int argc, const char * argv[]) { int r,g,b; rgb_from_hex("#123456", &r, &g, &b); printf("r=%d, g=%d, b=%d\n", r, g, b); } (The function will probably only correctly handle RGB, not RGBA.) A: The maximum of the red, green, and blue components seems to determine the "brightness" of a color in the HSB sense. A: In addition to the above, this is another solution, put together from others' answers here and elsewhere . - (BOOL)hasDkBg { NSScanner* scanner = [NSScanner scannerWithString:@"BD8F60"]; int hex; if ([scanner scanHexInt:&hex]) { // Parsing successful. We have a big int representing the 0xBD8F60 value int r = (hex >> 16) & 0xFF; // get the first byte int g = (hex >> 8) & 0xFF; // get the middle byte int b = (hex ) & 0xFF; // get the last byte int lightness = ((r*299)+(g*587)+(b*114))/1000; //get lightness value if (lightness < 127) { //127 = middle of possible lightness value return YES; } else return NO; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7615953", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Link calling a jQuery function doesn't seem to be working I am a jQuery newb so this is probably rudimentary. I have a test page here: http://www.problemio.com where I am trying to make links to vote up or down. Here is how the links look like: <a class="link_button" id="vote_up">Vote Up</a> <a class="link_button" id="vote_down">Vote Down</a> I use the class attribute for styling all over the site with that link_button so I decided to use the id attribute to distinguish the link for the jQuery call. Here is how my jQuery function looks like: $('a.vote_up').click(function() { alert("up"); }); Right now I just want to make sure it is getting called properly. But the alert isn't getting called which is making me think this is broken somewhere. Any idea how I can get this working? Thanks! A: You're using the class selector . instead of the id selector #. Hence do either $('#vote_up').click(function(){ alert("up"); }); or $('.link_button').click(function(){ if( this.id === 'vote_up' ) alert('vote up'); else if ( this.id === 'vote_down' ) alert('vote down'); } EDIT: also make sure everything is in a $(document).ready... i.e $(function(){ $('#vote_up').click(function(){ alert("up"); }); }); A: Your current selector is incorrect, it is looking for an a tag with a class of vote_up not it's id... use this instead... $(function() { $('#vote_up')... }); A: Have you tried the id selector? $('#vote_up').click(function() { alert('up'); }); A: a.vote_up looks for an <a> tag with the class vote_up. In your HTML vote_up is an ID, so you want this: $('#vote_up').click(function()
{ "language": "en", "url": "https://stackoverflow.com/questions/7615956", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why are operators so much slower than method calls? (structs are slower only on older JITs) Intro: I write high-performance code in C#. Yes, I know C++ would give me better optimization, but I still choose to use C#. I do not wish to debate that choice. Rather, I'd like to hear from those who, like me, are trying to write high-performance code on the .NET Framework. Questions: * *Why is the operator in the code below slower than the equivalent method call?? *Why is the method passing two doubles in the code below faster than the equivalent method passing a struct that has two doubles inside? (A: older JITs optimize structs poorly) *Is there a way to get the .NET JIT Compiler to treat simple structs as efficiently as the members of the struct? (A: get newer JIT) What I think I know: The original .NET JIT Compiler would not inline anything that involved a struct. Bizarre given structs should only be used where you need small value types that should be optimized like built-ins, but true. Fortunately, in .NET 3.5SP1 and .NET 2.0SP2, they made some improvements to the JIT Optimizer, including improvements to inlining, particularly for structs. (I am guessing they did that because otherwise the new Complex struct that they were introducing would have performed horribly... so the Complex team was probably pounding on the JIT Optimizer team.) So, any documentation prior to .NET 3.5 SP1 is probably not too relevant to this issue. What my testing shows: I have verified that I do have the newer JIT Optimizer by checking that C:\Windows\Microsoft.NET\Framework\v2.0.50727\mscorwks.dll file does have version >= 3053 and so should have those improvements to the JIT optimizer. However, even with that, what my timings and looks at the disassembly both show are: The JIT-produced code for passing a struct with two doubles is far less efficient than code that directly passes the two doubles. The JIT-produced code for a struct method passes in 'this' far more efficiently than if you passed a struct as an argument. The JIT still inlines better if you pass two doubles rather than passing a struct with two doubles, even with the multiplier due to being clearly in a loop. The Timings: Actually, looking at the disassembly I realize that most of the time in the loops is just accessing the test data out of the List. The difference between the four ways of making the same calls is dramatically different if you factor out the overhead code of the loop and the accessing of the data. I get anywhere from 5x to 20x speedups for doing PlusEqual(double, double) instead of PlusEqual(Element). And 10x to 40x for doing PlusEqual(double, double) instead of operator +=. Wow. Sad. Here's one set of timings: Populating List<Element> took 320ms. The PlusEqual() method took 105ms. The 'same' += operator took 131ms. The 'same' -= operator took 139ms. The PlusEqual(double, double) method took 68ms. The do nothing loop took 66ms. The ratio of operator with constructor to method is 124%. The ratio of operator without constructor to method is 132%. The ratio of PlusEqual(double,double) to PlusEqual(Element) is 64%. If we remove the overhead time for the loop accessing the elements from the List... The ratio of operator with constructor to method is 166%. The ratio of operator without constructor to method is 187%. The ratio of PlusEqual(double,double) to PlusEqual(Element) is 5%. The Code: namespace OperatorVsMethod { public struct Element { public double Left; public double Right; public Element(double left, double right) { this.Left = left; this.Right = right; } public static Element operator +(Element x, Element y) { return new Element(x.Left + y.Left, x.Right + y.Right); } public static Element operator -(Element x, Element y) { x.Left += y.Left; x.Right += y.Right; return x; } /// <summary> /// Like the += operator; but faster. /// </summary> public void PlusEqual(Element that) { this.Left += that.Left; this.Right += that.Right; } /// <summary> /// Like the += operator; but faster. /// </summary> public void PlusEqual(double thatLeft, double thatRight) { this.Left += thatLeft; this.Right += thatRight; } } [TestClass] public class UnitTest1 { [TestMethod] public void TestMethod1() { Stopwatch stopwatch = new Stopwatch(); // Populate a List of Elements to multiply together int seedSize = 4; List<double> doubles = new List<double>(seedSize); doubles.Add(2.5d); doubles.Add(100000d); doubles.Add(-0.5d); doubles.Add(-100002d); int size = 2500000 * seedSize; List<Element> elts = new List<Element>(size); stopwatch.Reset(); stopwatch.Start(); for (int ii = 0; ii < size; ++ii) { int di = ii % seedSize; double d = doubles[di]; elts.Add(new Element(d, d)); } stopwatch.Stop(); long populateMS = stopwatch.ElapsedMilliseconds; // Measure speed of += operator (calls ctor) Element operatorCtorResult = new Element(1d, 1d); stopwatch.Reset(); stopwatch.Start(); for (int ii = 0; ii < size; ++ii) { operatorCtorResult += elts[ii]; } stopwatch.Stop(); long operatorCtorMS = stopwatch.ElapsedMilliseconds; // Measure speed of -= operator (+= without ctor) Element operatorNoCtorResult = new Element(1d, 1d); stopwatch.Reset(); stopwatch.Start(); for (int ii = 0; ii < size; ++ii) { operatorNoCtorResult -= elts[ii]; } stopwatch.Stop(); long operatorNoCtorMS = stopwatch.ElapsedMilliseconds; // Measure speed of PlusEqual(Element) method Element plusEqualResult = new Element(1d, 1d); stopwatch.Reset(); stopwatch.Start(); for (int ii = 0; ii < size; ++ii) { plusEqualResult.PlusEqual(elts[ii]); } stopwatch.Stop(); long plusEqualMS = stopwatch.ElapsedMilliseconds; // Measure speed of PlusEqual(double, double) method Element plusEqualDDResult = new Element(1d, 1d); stopwatch.Reset(); stopwatch.Start(); for (int ii = 0; ii < size; ++ii) { Element elt = elts[ii]; plusEqualDDResult.PlusEqual(elt.Left, elt.Right); } stopwatch.Stop(); long plusEqualDDMS = stopwatch.ElapsedMilliseconds; // Measure speed of doing nothing but accessing the Element Element doNothingResult = new Element(1d, 1d); stopwatch.Reset(); stopwatch.Start(); for (int ii = 0; ii < size; ++ii) { Element elt = elts[ii]; double left = elt.Left; double right = elt.Right; } stopwatch.Stop(); long doNothingMS = stopwatch.ElapsedMilliseconds; // Report results Assert.AreEqual(1d, operatorCtorResult.Left, "The operator += did not compute the right result!"); Assert.AreEqual(1d, operatorNoCtorResult.Left, "The operator += did not compute the right result!"); Assert.AreEqual(1d, plusEqualResult.Left, "The operator += did not compute the right result!"); Assert.AreEqual(1d, plusEqualDDResult.Left, "The operator += did not compute the right result!"); Assert.AreEqual(1d, doNothingResult.Left, "The operator += did not compute the right result!"); // Report speeds Console.WriteLine("Populating List<Element> took {0}ms.", populateMS); Console.WriteLine("The PlusEqual() method took {0}ms.", plusEqualMS); Console.WriteLine("The 'same' += operator took {0}ms.", operatorCtorMS); Console.WriteLine("The 'same' -= operator took {0}ms.", operatorNoCtorMS); Console.WriteLine("The PlusEqual(double, double) method took {0}ms.", plusEqualDDMS); Console.WriteLine("The do nothing loop took {0}ms.", doNothingMS); // Compare speeds long percentageRatio = 100L * operatorCtorMS / plusEqualMS; Console.WriteLine("The ratio of operator with constructor to method is {0}%.", percentageRatio); percentageRatio = 100L * operatorNoCtorMS / plusEqualMS; Console.WriteLine("The ratio of operator without constructor to method is {0}%.", percentageRatio); percentageRatio = 100L * plusEqualDDMS / plusEqualMS; Console.WriteLine("The ratio of PlusEqual(double,double) to PlusEqual(Element) is {0}%.", percentageRatio); operatorCtorMS -= doNothingMS; operatorNoCtorMS -= doNothingMS; plusEqualMS -= doNothingMS; plusEqualDDMS -= doNothingMS; Console.WriteLine("If we remove the overhead time for the loop accessing the elements from the List..."); percentageRatio = 100L * operatorCtorMS / plusEqualMS; Console.WriteLine("The ratio of operator with constructor to method is {0}%.", percentageRatio); percentageRatio = 100L * operatorNoCtorMS / plusEqualMS; Console.WriteLine("The ratio of operator without constructor to method is {0}%.", percentageRatio); percentageRatio = 100L * plusEqualDDMS / plusEqualMS; Console.WriteLine("The ratio of PlusEqual(double,double) to PlusEqual(Element) is {0}%.", percentageRatio); } } } The IL: (aka. what some of the above gets compiled into) public void PlusEqual(Element that) { 00000000 push ebp 00000001 mov ebp,esp 00000003 push edi 00000004 push esi 00000005 push ebx 00000006 sub esp,30h 00000009 xor eax,eax 0000000b mov dword ptr [ebp-10h],eax 0000000e xor eax,eax 00000010 mov dword ptr [ebp-1Ch],eax 00000013 mov dword ptr [ebp-3Ch],ecx 00000016 cmp dword ptr ds:[04C87B7Ch],0 0000001d je 00000024 0000001f call 753081B1 00000024 nop this.Left += that.Left; 00000025 mov eax,dword ptr [ebp-3Ch] 00000028 fld qword ptr [ebp+8] 0000002b fadd qword ptr [eax] 0000002d fstp qword ptr [eax] this.Right += that.Right; 0000002f mov eax,dword ptr [ebp-3Ch] 00000032 fld qword ptr [ebp+10h] 00000035 fadd qword ptr [eax+8] 00000038 fstp qword ptr [eax+8] } 0000003b nop 0000003c lea esp,[ebp-0Ch] 0000003f pop ebx 00000040 pop esi 00000041 pop edi 00000042 pop ebp 00000043 ret 10h public void PlusEqual(double thatLeft, double thatRight) { 00000000 push ebp 00000001 mov ebp,esp 00000003 push edi 00000004 push esi 00000005 push ebx 00000006 sub esp,30h 00000009 xor eax,eax 0000000b mov dword ptr [ebp-10h],eax 0000000e xor eax,eax 00000010 mov dword ptr [ebp-1Ch],eax 00000013 mov dword ptr [ebp-3Ch],ecx 00000016 cmp dword ptr ds:[04C87B7Ch],0 0000001d je 00000024 0000001f call 75308159 00000024 nop this.Left += thatLeft; 00000025 mov eax,dword ptr [ebp-3Ch] 00000028 fld qword ptr [ebp+10h] 0000002b fadd qword ptr [eax] 0000002d fstp qword ptr [eax] this.Right += thatRight; 0000002f mov eax,dword ptr [ebp-3Ch] 00000032 fld qword ptr [ebp+8] 00000035 fadd qword ptr [eax+8] 00000038 fstp qword ptr [eax+8] } 0000003b nop 0000003c lea esp,[ebp-0Ch] 0000003f pop ebx 00000040 pop esi 00000041 pop edi 00000042 pop ebp 00000043 ret 10h A: I'm getting very different results, much less dramatic. But didn't use the test runner, I pasted the code into a console mode app. The 5% result is ~87% in 32-bit mode, ~100% in 64-bit mode when I try it. Alignment is critical on doubles, the .NET runtime can only promise an alignment of 4 on a 32-bit machine. Looks to me the test runner is starting the test methods with a stack address that's aligned to 4 instead of 8. The misalignment penalty gets very large when the double crosses a cache line boundary. A: I'm having some difficulty replicating your results. I took your code: * *made it a standalone console application *built an optimized (release) build *increased the "size" factor from 2.5M to 10M *ran it from the command line (outside the IDE) When I did so, I got the following timings which are far different from yours. For the avoidance of doubt, I'll post exactly the code I used. Here are my timings Populating List<Element> took 527ms. The PlusEqual() method took 450ms. The 'same' += operator took 386ms. The 'same' -= operator took 446ms. The PlusEqual(double, double) method took 413ms. The do nothing loop took 229ms. The ratio of operator with constructor to method is 85%. The ratio of operator without constructor to method is 99%. The ratio of PlusEqual(double,double) to PlusEqual(Element) is 91%. If we remove the overhead time for the loop accessing the elements from the List... The ratio of operator with constructor to method is 71%. The ratio of operator without constructor to method is 98%. The ratio of PlusEqual(double,double) to PlusEqual(Element) is 83%. And these are my edits to your code: namespace OperatorVsMethod { public struct Element { public double Left; public double Right; public Element(double left, double right) { this.Left = left; this.Right = right; } public static Element operator +(Element x, Element y) { return new Element(x.Left + y.Left, x.Right + y.Right); } public static Element operator -(Element x, Element y) { x.Left += y.Left; x.Right += y.Right; return x; } /// <summary> /// Like the += operator; but faster. /// </summary> public void PlusEqual(Element that) { this.Left += that.Left; this.Right += that.Right; } /// <summary> /// Like the += operator; but faster. /// </summary> public void PlusEqual(double thatLeft, double thatRight) { this.Left += thatLeft; this.Right += thatRight; } } public class UnitTest1 { public static void Main() { Stopwatch stopwatch = new Stopwatch(); // Populate a List of Elements to multiply together int seedSize = 4; List<double> doubles = new List<double>(seedSize); doubles.Add(2.5d); doubles.Add(100000d); doubles.Add(-0.5d); doubles.Add(-100002d); int size = 10000000 * seedSize; List<Element> elts = new List<Element>(size); stopwatch.Reset(); stopwatch.Start(); for (int ii = 0; ii < size; ++ii) { int di = ii % seedSize; double d = doubles[di]; elts.Add(new Element(d, d)); } stopwatch.Stop(); long populateMS = stopwatch.ElapsedMilliseconds; // Measure speed of += operator (calls ctor) Element operatorCtorResult = new Element(1d, 1d); stopwatch.Reset(); stopwatch.Start(); for (int ii = 0; ii < size; ++ii) { operatorCtorResult += elts[ii]; } stopwatch.Stop(); long operatorCtorMS = stopwatch.ElapsedMilliseconds; // Measure speed of -= operator (+= without ctor) Element operatorNoCtorResult = new Element(1d, 1d); stopwatch.Reset(); stopwatch.Start(); for (int ii = 0; ii < size; ++ii) { operatorNoCtorResult -= elts[ii]; } stopwatch.Stop(); long operatorNoCtorMS = stopwatch.ElapsedMilliseconds; // Measure speed of PlusEqual(Element) method Element plusEqualResult = new Element(1d, 1d); stopwatch.Reset(); stopwatch.Start(); for (int ii = 0; ii < size; ++ii) { plusEqualResult.PlusEqual(elts[ii]); } stopwatch.Stop(); long plusEqualMS = stopwatch.ElapsedMilliseconds; // Measure speed of PlusEqual(double, double) method Element plusEqualDDResult = new Element(1d, 1d); stopwatch.Reset(); stopwatch.Start(); for (int ii = 0; ii < size; ++ii) { Element elt = elts[ii]; plusEqualDDResult.PlusEqual(elt.Left, elt.Right); } stopwatch.Stop(); long plusEqualDDMS = stopwatch.ElapsedMilliseconds; // Measure speed of doing nothing but accessing the Element Element doNothingResult = new Element(1d, 1d); stopwatch.Reset(); stopwatch.Start(); for (int ii = 0; ii < size; ++ii) { Element elt = elts[ii]; double left = elt.Left; double right = elt.Right; } stopwatch.Stop(); long doNothingMS = stopwatch.ElapsedMilliseconds; // Report speeds Console.WriteLine("Populating List<Element> took {0}ms.", populateMS); Console.WriteLine("The PlusEqual() method took {0}ms.", plusEqualMS); Console.WriteLine("The 'same' += operator took {0}ms.", operatorCtorMS); Console.WriteLine("The 'same' -= operator took {0}ms.", operatorNoCtorMS); Console.WriteLine("The PlusEqual(double, double) method took {0}ms.", plusEqualDDMS); Console.WriteLine("The do nothing loop took {0}ms.", doNothingMS); // Compare speeds long percentageRatio = 100L * operatorCtorMS / plusEqualMS; Console.WriteLine("The ratio of operator with constructor to method is {0}%.", percentageRatio); percentageRatio = 100L * operatorNoCtorMS / plusEqualMS; Console.WriteLine("The ratio of operator without constructor to method is {0}%.", percentageRatio); percentageRatio = 100L * plusEqualDDMS / plusEqualMS; Console.WriteLine("The ratio of PlusEqual(double,double) to PlusEqual(Element) is {0}%.", percentageRatio); operatorCtorMS -= doNothingMS; operatorNoCtorMS -= doNothingMS; plusEqualMS -= doNothingMS; plusEqualDDMS -= doNothingMS; Console.WriteLine("If we remove the overhead time for the loop accessing the elements from the List..."); percentageRatio = 100L * operatorCtorMS / plusEqualMS; Console.WriteLine("The ratio of operator with constructor to method is {0}%.", percentageRatio); percentageRatio = 100L * operatorNoCtorMS / plusEqualMS; Console.WriteLine("The ratio of operator without constructor to method is {0}%.", percentageRatio); percentageRatio = 100L * plusEqualDDMS / plusEqualMS; Console.WriteLine("The ratio of PlusEqual(double,double) to PlusEqual(Element) is {0}%.", percentageRatio); } } } A: Running .NET 4.0 here. I compiled with "Any CPU", targeting .NET 4.0 in release mode. Execution was from the command line. It ran in 64-bit mode. My timings are a bit different. Populating List<Element> took 442ms. The PlusEqual() method took 115ms. The 'same' += operator took 201ms. The 'same' -= operator took 200ms. The PlusEqual(double, double) method took 129ms. The do nothing loop took 93ms. The ratio of operator with constructor to method is 174%. The ratio of operator without constructor to method is 173%. The ratio of PlusEqual(double,double) to PlusEqual(Element) is 112%. If we remove the overhead time for the loop accessing the elements from the List ... The ratio of operator with constructor to method is 490%. The ratio of operator without constructor to method is 486%. The ratio of PlusEqual(double,double) to PlusEqual(Element) is 163%. In particular, PlusEqual(Element) is slightly faster than PlusEqual(double, double). Whatever the problem is in .NET 3.5, it doesn't appear to exist in .NET 4.0. A: Like @Corey Kosak, I just ran this code in VS 2010 Express as a simple Console App in Release mode. I get very different numbers. But I also have Fx4.5 so these might not be the results for a clean Fx4.0 . Populating List<Element> took 435ms. The PlusEqual() method took 109ms. The 'same' += operator took 217ms. The 'same' -= operator took 157ms. The PlusEqual(double, double) method took 118ms. The do nothing loop took 79ms. The ratio of operator with constructor to method is 199%. The ratio of operator without constructor to method is 144%. The ratio of PlusEqual(double,double) to PlusEqual(Element) is 108%. If we remove the overhead time for the loop accessing the elements from the List ... The ratio of operator with constructor to method is 460%. The ratio of operator without constructor to method is 260%. The ratio of PlusEqual(double,double) to PlusEqual(Element) is 130%. Edit: and now run from the cmd line. That does make a difference, and less variation in the numbers. A: In addition to JIT compiler differences mentioned in other answers, another difference between a struct method call and a struct operator is that a struct method call will pass this as a ref parameter (and may be written to accept other parameters as ref parameters as well), while a struct operator will pass all operands by value. The cost to pass a structure of any size as a ref parameter is fixed, no matter how large the structure is, while the cost to pass larger structures is proportional to structure size. There is nothing wrong with using large structures (even hundreds of bytes) if one can avoid copying them unnecessarily; while unnecessary copies can often be prevented when using methods, they cannot be prevented when using operators. A: Not sure if this is relevant, but here's the numbers for .NET 4.0 64-bit on Windows 7 64-bit. My mscorwks.dll version is 2.0.50727.5446. I just pasted the code into LINQPad and ran it from there. Here's the result: Populating List<Element> took 496ms. The PlusEqual() method took 189ms. The 'same' += operator took 295ms. The 'same' -= operator took 358ms. The PlusEqual(double, double) method took 148ms. The do nothing loop took 103ms. The ratio of operator with constructor to method is 156%. The ratio of operator without constructor to method is 189%. The ratio of PlusEqual(double,double) to PlusEqual(Element) is 78%. If we remove the overhead time for the loop accessing the elements from the List ... The ratio of operator with constructor to method is 223%. The ratio of operator without constructor to method is 296%. The ratio of PlusEqual(double,double) to PlusEqual(Element) is 52%. A: I would imagine as when you are accessing members of the struct, that it is infact doing an extra operation to access the member, the THIS pointer + offset. A: May be instead of List you should use double[] with "well known" offsets and index increments?
{ "language": "en", "url": "https://stackoverflow.com/questions/7615959", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "85" }
Q: DataInputStream stuck on readFully I have a BluetoothSocket that I am reading data from, using a separate Thread process from the GUI. I wrap the InputStream in DataInputStream so I can do use a a readFully(..) to wait for a specified amount of data. I can run this code for about an hour and then the program locks up and when I debug its stuck at the readFully(). I included in my GUI thread BroadcastReceivers to notify me when the bluetooth disconnects. The BroadCastReceivers never get notified. Not sure why the device just stops sending data if that is the case or not eve sure if the Bluetooth SPP gets dropped but the socket is still open so the Bluetooth Disconnect message never happens. Any ideas as to the fix or even why or how to debug why its stuck would be appreciated. Here is my ReadBlueTooth class... public class ReadBlueToothData extends Thread { private BluetoothSocket btSocket; private BluetoothAdapter bta; private DataInputStream dinput; public ReadBlueToothData(Activity a,String mac) { ...init object... } public void run() { // if socket connected otherwise stop if (dinput==null) return; byte[] byteArray = new byte[3]; while (!Thread.interrupted()) { dinput.readFully(byteArray, 0, 3); // DO something .... } // close out InputStream nicely if (dinput!=null) { try { dinput.close(); } catch (IOException e) { } } if (btSocket != null) { try { btSocket.close(); } catch (IOException e) {} } } } A: I don't get this error anymore by doing this gracefully when detecting a Bluetooth disconnect. dinput.close(); readBlueToothData().interrupt(); btSocket.close(); //make sure to check for nulls for all these too and also then do a check by looking at the data coming in and if the buffer doesn't increase in size then also call disconnect.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615960", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can CacheBuilder replace MapMaker in my case? I need to obtain the result of the slow method slowResult() for instances of the class Something. Caching alone doesn't help as the instances hardly ever repeat. Fortunately, I know that the result depends actually only on some easily obtained Attributes of Something, so I could use a Map<Attributes, Result> as a cache, in code Result fastResult(Something something) { final Attributes attributes = attributesFor(something) Result result = cache.get(attributes); if (result!=null) return result; result = something.slowResult(); cache.put(attributes, result); return result; } In order to keep the cache limited I used the now deprecated methods maximumSize and expireAfterAccess. The deprecation comes because of the new class CacheBuilder to be used instead. However, I've found no nice way how to apply it to my case. The cache keys need to be instances of Attributes, but in cache loading an instance of Something is needed and there's no easy way to recreate it from the Attributes. Is there a nice solution to this problem? A: Very interesting! I don't think we had ever heard of a case like this. For 11.0 you'll be able to do cache.asMap().put(), so it would probably be okay to just ignore the deprecation warnings for now. We are considering possibly enabling that in a 10.1 patch release because several users seem to be in a similar boat. But, in 11.0 the other idea we're kicking around would allow you to do this: Result fastResult(final Something something) { return cache.get( attributesFor(something), new Callable<Result>() { public Result call() { return something.slowResult(); } }); } A: Can you just key the Cache off of Something instead? A: Well, one way to state this problem is, "how can I compare Attributes.equals() for the cache, but still have access to Something to create the value". So, I think this might work ... class SomethingKey { private Something something; private final Attributes attributes; SomethingKey(Something s) { this.something = s; this.attributes = attributesFor(something); } public Result createResult() { Something something = this.s; this.s = null; return something.slowResult(); } public boolean equals(Object o) { if(o==this) return true; if(o==null || o.getClass() != this.getClass) return false; SomethingKey that = (SomethingKey)o; return this.attributes.equals(that.attributes); } } And then CacheLoader.load is basically Result load(SomethingKey k) { return k.createResult(); } And the map would be Cache<SomethingKey,Result> map = ...; Of course, the downside is you're creating a new SomethingKey per request, but...
{ "language": "en", "url": "https://stackoverflow.com/questions/7615961", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP: Easy way to start PayPal checkout? I have completely functional cart solution. All I want is the code where I actually pass the name of the products, the total, the return address and my paypal address so that it can direct me to a shopping cart. Can anyone steer me in the right direction? PayPal has a million different versions. What I've come to learn is that the one I need is called "paypal website payments". Can someone confirm this? A: Yes, the Website Payments Standard is the way to go. Basically, you create a form that has a few hidden fields ready to go (such as amount and what not) and then submit it. You could even submit this with JavaScript, so it takes your customer right to PayPal to complete the transaction. As an example: <form action="https://www.paypal.com/cgi-bin/webscr" method="post"> <input type="hidden" name="cmd" value="_xclick" /> <input type="hidden" name="business" value="your_paypal_email_account" /> <input type="hidden" name="undefined_quantity" value="1" /> <input type="hidden" name="item_name" value="Order #1111111 for So-and-So" /> <input type="hidden" name="item_number" value="order_1111111" /> <input type="hidden" name="amount" value="5.00" /> <input type="hidden" name="shipping" value="0.00" /> <input type="hidden" name="no_shipping" value="1" /> <input type="hidden" name="cn" value="Comments" /> <input type="hidden" name="currency_code" value="USD" /> <input type="hidden" name="lc" value="US" /> <input type="hidden" name="bn" value="PP-BuyNowBF" /> <input type="hidden" name="return" value="http://www.example.com/some-page-to-return-to" /> <input type="image" src="https://www.paypal.com/en_US/i/btn/btn_buynow_SM.gif" border="0" name="submit" alt="Make payments with PayPal - it's fast, free and secure!" /> <img alt="" border="0" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1" /> </form> You can find documentation on the additional parameters available here: https://www.x.com/sites/default/files/pp_websitepaymentsstandard_integrationguide.pdf A: You can use as a reference the following source code: https://github.com/osCommerce/oscommerce2/blob/master/catalog/ext/modules/payment/paypal/express.php Check out this comparison of PayPal merchant solutions: https://www.paypal.com/gr/cgi-bin/webscr?cmd=_profile-comparison
{ "language": "en", "url": "https://stackoverflow.com/questions/7615964", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: qt menu item does not show I'm writing a window manager and I'm stuck with a problem on Qt4 menu bar elements. When I first click on the menu item, it shows correctly, then I close it and try to open it again but it does not show anymore. If I try to open another menu item, it works for the first time and then that item cannot be shown again too. I tried a lot of tricks like changing focus, resizing or moving the window, but it does not work. I tried with a couple of Qt applications (smplayer and QtOctave) and all have the same issue on the menu bar. I also tested GIMP and xfe (which run on gtk, just to countercheck) and their menus work correctly. I did not test any Qt3 application yet, but I guess they behave the same way. Note: It gives me the same issue with Qt4 context menus. Note: The menu itself works, but it's invisible after the first time..
{ "language": "en", "url": "https://stackoverflow.com/questions/7615971", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: XmlSearch does not recognize xPath I have an xml document like so <cfxml variable="mydoc"> <?xml version="1.0" encoding="UTF-8"?> <Feed xmlns="http://www.example.com/xs/PRR/SyndicationFeed/4.9" name="Test"> <Product id="test1" removed="false"> <Source>Widget</Source> <ExternalId>Widget01</ExternalId> <Name>iWidget 3G</Name> <NumReviews>11</NumReviews> </product> </Feed> </cfxml> I want to return the NumReviews node text. However: numReviews = XmlSearch(mydoc, "/Feed/Product/NumReviews"); returns an empty array. While numReviews = XmlSearch(myDoc, "//*[local-name()='NumReviews']"); returns the node text. As far as I can tell, the first line of code is correct and should return the value of NumReviews. Why is it instead returning an empty array? A: Something like numReviews = XmlSearch(mydoc, "/:Feed/:Product/:NumReviews"); also should work when there are namespaces. A: And it may be the name spaces. I think your second syntax is required when namespaces are involved. I know I've had to use it myself. A: You are using backslashes in the first example. They should be frontslashes, right?
{ "language": "en", "url": "https://stackoverflow.com/questions/7615972", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: isql wait for end of query on iphone i'm using isql sdk to make Microsoft Sql 2008 query through iphone, everything works fine but I always need to click two button to get the answer of my query. I press the button 'submit' then i can press the button 'next page' and the result will show on the next page but if i put my query in the next page button, the app switch to the next page but since the query isn't finished my text view is empty, so is there a way to make the app wait for the end of a query, it would be great if the entire app could pause and an activity indicator shows up until the query finish A: To make my app wait for the query to finish I use something like SVProgressHUD https://github.com/samvermette/SVProgressHUD Basically when I execute the query I display the hud (which halts user interaction) Then when the query finishes I deal with the data returned (change views, update textfields, etc.) then dismiss the HUD.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615982", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make .gitignore ignore compiled files with no extension? Possible Duplicate: gitignore without binary files Edit: Dupe of gitignore without binary files When you compile, say, a Haskell file, (test.hs), using ghc --make test.hs, the result is test.hi and test. I only want to add and commit the source test.hs, while keeping test.hi and test out of the repository but in the same directory as the source file. test is the problem, how do I specify to .gitignore to ignore a compiled file with no extension? A: Just add the filename to your .gitignore file. For example: $ git ls-files --other --exclude-standard test $ echo test > .gitignore $ git ls-files --other --exclude-standard $ .gitignore doesn't care about extensions. It just matches patterns.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615983", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: Footer on a multi horizontal-div website I wasn't really sure how to put divs beside each other. I found a solution here, however, instead of subsequent text going below (where it should) the text now aligns to the right. This wouldn't normally be a problem because all of the content is inside the main container, however, I want my footer to appear at the bottom of the page. Here is the website: http://www.winterlb.com/test/ The "test" at the right is what I want to appear at the bottom of the page, thanks. A: add <div style="clear: both;"></div> above your footer div
{ "language": "en", "url": "https://stackoverflow.com/questions/7615988", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Mouse side buttons in python? I am trying to use my mouse as remote on my laptop and I would like to use side buttons in them. I am coding in python as I have already succeeded doing it with autohotkey. But autohotkey uses too much resources. The mouse is Razer Orochi.. It has 7 buttons and a scrollwheel. I would like to use left side front key for modifier and lbutton, rbutton, mbutton and wheel as secondary... also by pressing both left side buttons I would like to lock the mouse until 4 buttons, all of them on sides are pressed... Yet I can't seem to figure out how to read input from side buttons on mouse in python. A: This isn't quite an answer, but maybe a set of references to start you out. I don't have experience with Python on Windows, but it looks like these might be helpful: * *there's a set of Windows Extensions for Python: pywin32. *Yak created a two-finger scrolling driver by reading the COM in a special way in Python here. Judging by how Yak got two-finger scrolling in his code, I imagine what you're doing is not so far off? I also think win32com would help you out. A: Final solution was made using PyHook Many thanks to Peter Parente.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615989", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Does mozillas firefox countless versions make GWT development impossible? There was no GWT plugin for firefox 6 and likely there won't be a release for firefox 7, because firefox 8 is already in beta. How can I develop a GWT app, when mozilla releases one firefox version after another? How can I ensure browser compatibility? A: I've been happy so far staying a version behind in Firefox for the plugin, and using compiled code for tests in newer versions. There is now an automatic update for the gwt plugin for Firefox 6, so someone is keeping something updated. PS: I've yet to notice a single-pixel difference in firefox rendering between recent versions! A: It does not make it impossible, it just makes it equivalent to regular development. You can still test it on the latest version of Firefox, as well as the other platforms for which the GWT plugin is available. Beta versions of browsers, latest versions (which do not yet have GWT plugins released), and obscure browsers will just need to be tested manually. A: For those who are impatient to wait for an official release, you can download a prebuilt from the code repository. It does the job with Firefox 7. GWT Plugin Prebuilt at Google Code
{ "language": "en", "url": "https://stackoverflow.com/questions/7615990", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Is there better explaination of the WCF RIA Services Library Project structure? When you create WCF RIA Services Library Project then two projects appears. * *RIAServicesLibrary1 *RIAServicesLibrary1.Web It's clear for me what for we need RIAServicesLibrary1.Web project to keep stuff like LinqToEntitiesDomainService? But my questions is: how we can use RIAServicesLibrary project? Is any real sense of it usage? A: The RIAServicesLibrary can be used for directly referencing in client applications that do not need to have to be deployed in a multi-tier environment (client-server). As soon as you want to have your client talk to a webservice on a central server you will communicate to the .Web variant, which has a direct reference to the library project.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615991", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Core data save an object with a relationship to an existing object in the database I am trying to save a new Object to my context, that will have a foreign key reference (relationship many-to-many) to an object already in the database. How can I set the relationship of this new Object to save it to the database?. I tried fetching that object and then setting it in the relationship, but that causes an error when saving the context that comes as null. I also tried recreating it as a new object, thinking core data would not create a new object but just add the relationship, however it did create the new Object. How can I save this object? A: You have to set the object in the relationship from your new object, the inverse relationship will then be set for you. So, you need to figure out what is causing the error you are seeing. In CoreData objects generated from mogenerator, the code to add a single object to a relationship set accesses a mutable set from the object property: NSMutableSet *result = [self mutableSetValueForKey:@"rounds"]; Then you can add your existing object to that set, and try saving the new object. Alternatley, CoreData for any ManagedObject generates a method: - (void)addRoundsObject:(Round*)value_; If you use that method it should also add the object correctly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615993", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Webpage does not resize with browser window resize A website I am developing for a client is having an odd issue. When the page is loaded, the page fills the whole browser window, but if the window is re-sized, the page stays its original dimensions with scroll-bars appearing, kind of like an overflow: hidden. I'm not sure why this is happening, here is the website: http://www.anthonygonzalez.com/ A: Your setStyle() function that's called when the body of your page loads is setting up the width, etc. statically (using pixels) based on the size of the browser window when the page is loaded. It doesn't appear to be updating those values when the window changes size. You either need to * *Use percentages instead of pixels when you do this or, *Call that same function whenever the browser is resized to re-calculate those values based on the new window size. Let me know if that doesn't help, or if I've missed something.
{ "language": "en", "url": "https://stackoverflow.com/questions/7615994", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using entity framework with Stored procedures and unnamed columns I am trying here to work with entity framework with unnamed columns within a stored procedure. Say for instance the following SP : CREATE PROCEDURE [dbo].[GetUsers] AS BEGIN SELECT Username, Firstname + ' ' + Lastname FROM dbo.users END GO Normally if I create a mapping in entity framework I have 2 columns in a complex object created (Username and Column1). The problem here is I try to use POCOs instead of auto-generated complex objects. With named columns the reflexion does the job. But when I include concatenated column It is not mapping the data. Is it possible to map it in any kind of way to an existing POCO [having Username and Fullname as existing properties for instance] ? (attributes, wizard or something else ?) A: Auto-generated objects are still POCOs if you use correct template so you can map procedure as function import and use complex type. Otherwise use what @marc_s suggested and give every computed column alias: SELECT Username, Firstname + ' ' + Lastname AS FullName FROM dbo.users
{ "language": "en", "url": "https://stackoverflow.com/questions/7615995", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: What is the JavaScript equivalent of MySQL's %LIKE% clause? In MySQL I use the like clause: LIKE %some keyword% to perform searches on database records. What can I use to similarly do a search in a JavaScript? So if a user enters something like ger it will show german shepard Can't use: str.search('ger'); since it seems to only match whole words A: I'm not sure exactly in what context you are using the like operator (e.g. a form field), but you probably want to take advantage of javascript's regular expression object. A simple example (in your case, for a LIKE query), might look like this: var regex = /.*ger.*/ var matchesRegex = regex.test(yourString); if (matchesRegex) { //do something } Alternatively, you can search for the incidence of your string using the indexOf operation: var matches = yourString.indexOf("ger") >= 0 ? true : false; if (matches) { //do something } A: it's not exact same as %LIKE% but you can use indexOf(). var str = "Mohsen", st = "Moh"; if(str.indexOf(st) > -1) // true A: search function does not only return whole words. Maybe you are getting confused by the fact it returns zero-based index, so... // this returns 0 as positive match at position 0 "german shepherd".search('ger') // this returns -1 as negative match "german shepherd".search('gerx') So you need to do comparison of result of search against -1 to see if it is a match or not - you can not just check for true/false. So you could do... if(str.search('ger') !== -1){ // matches string } else { // does not match string } // or another way // add one to convert result to one-based index, and check truthiness if(str.search('ger')+1){ // there is a match } else { // there is not a match } A: Assuming you've got a bunch of records as an array of strings you can use the JavaScript built-in Array.filter method: var ss = ['german shepard', 'labrador', 'chihuahua']; var matches = ss.filter(function(s) { return s.match(/ger/); }); matches; //output => ['german shepard'] Or if your target JavaScript doesn't implement that method (e.g. it implements ECMAScript prior to 5th edition), then you can do a simple array search, e.g: var searchArray = function(arr, regex) { var matches=[], i; for (i=0; i<arr.length; i++) { if (arr[i].match(regex)) matches.push(arr[i]); } return matches; }; searchArray(ss, /h/); //output => ['german shepard', 'chihuahua'] A: I'm not sure if all browsers support all of these methods: http://www.javascriptkit.com/jsref/string.shtml But it looks like there's a String.match() method that'll do what you want. A: Here is an easy way to do it in JQuery. This uses a filtering of text data inside of a table via a data-filter on the table row, but it can easily be used for other purposes. $('#search').on('keyup', function() { var val = $.trim(this.value); if (val) { $('tr[data-filter!=' + val + ']').hide(); $('tr[data-filter^=' + val + ']').show(); } else { $('tr[data-filter]').show(); } }); In this example it will hide all table rows where an exact match wasn't found, and then filter by the start of the string value. The trim() function is useful in case all that's there is empty spaces, then it will still display everything as if a search was never made. If you want it to display the searched input where it's anywhere on the string, use a * instead of a ^. Both special characters are case sensitive. Also be sure that the hide command displays first and that both are present, or it won't work properly. See another example here that utilizes both the ^ and * characters: http://jsfiddle.net/heatwaveo8/2VKae/ A: my code: // file name 1 = "E_000096_01.jpg" // file name 2 = "E_000096_02.jpg" // file name 3 = "E_000096_03.jpg" // file name 4 = "E_000095_01.jpg" var code = "000096"; var files = fs.readdirSync(dir).filter(file => file.indexOf(code) >= 0 ? true : false) // result console.log(files) //["E_000096_01.jpg","E_000096_02.jpg","E_000096_03.jpg"] A: I assume you have data came from database let say it is like let names = ['yusuf', 'sabri', 'bayrakdar']; You should use includes within a filter: let searchValue = 'usu' let filteredNames = names.filter(name => name.includes(searchValue)); filteredNames is going to be ["yusuf"]
{ "language": "en", "url": "https://stackoverflow.com/questions/7615997", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: UIAlert visual slow-down when UINavigationController popping I have a UIAlert appear just before the UINavigationController pops a view controller off the stack. This causes a very visible slow-down; the current view darkens, pauses, slides to the new view, and then at last the UIAlert appears. The slow-down is entirely undesirable; it looks terrible. Programmatically I need to fire the UIAlert before the view controller transition (although I do not need to wait for user interaction w/the UIAlert to continue) because that's where the data is. So do I (a) make the data accessible to after-the-view-controller-pop and fire UIAlert then, (b) add some sort of time or function delay to the UIAlert so that it fires after-the-view-controller-pop, or (c) some otehr good suggestion? A: Use performSelector:withObject:afterDelay: [self performSelector:@selector(methodThatShowsAlert) withObject:nil afterDelay:0.5];
{ "language": "en", "url": "https://stackoverflow.com/questions/7615998", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Searching by each word rather than complete string using MYSQL PHP My search allows users to search games in my database. The only problem is that if a user types multiple terms within the search, it will only get hits if those multiple words are right next to each other. Example: searched term = Call Duty Modern result = none BUT if they input: searched term = Call of Duty -or- Modern Warfare result = Call of Duty Modern Warfare 1/2/3 etc. here is my mysql query: $query = "SELECT ID, title FROM games WHERE title LIKE '%{$title}%' AND platform = :platform LIMIT $startFrom,15"; $statement = $dbG->prepare($query); $statement->bindValue(':platform', $platform); $statement->execute(); $gamesLike = $statement->fetch(PDO::FETCH_ASSOC); I know i should break up each word and search each term but im afraid it would eat up all my programs speed... are there any specific MYSQL query tweaks i can use to achieve the result i need? Any suggestions would be greatly appreciated Thank you for your time A: full text searching is great for this: http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html It essentially turns mysql into a search engine where you use match and against to get a rank back of how often the search terms show up in the column you are matching against. It can handle partial matches, multiple matches, excludes words that are small/common to help performance and allows for search keywords/symbols like +some -search will return results that must have some but can't have search. Also it is surprisingly easy to setup as pretty much everything you need works by default.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616000", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Forcing x axis to align with y axis in Mathematica Plot In Mathematica, when I plot things sometimes I don't always get the x-axis to line up with the exact bottom of the plot. Is there any way I can force it to do this all the time? Here's an example of what I'm talking about: http://i.imgur.com/3lcWd.png I want the x-axis to line up perfectly with the zero tick mark way at the bottom, not in the middle of the y-axis as it is in that image. Any way I can accomplish this? A: Use the option AxesOrigin -> {0,0} A: The following will draw your Axes on the left and bottom, irrespective to the coordinate values: aPlot[f_, var_, opts : OptionsPattern[]] := Plot[f, var, AxesOrigin -> First /@ (# /. AbsoluteOptions[Plot[f, var, opts], #] &@PlotRange), opts] aPlot[Evaluate[Table[BesselJ[n, x], {n, 4}]], {x, 0, 10}, Filling -> Axis] aPlot[Sin[x], {x, 0, 2 Pi}] A: You could also use something like: Frame -> {{Automatic, None}, {Automatic, None}} (Also I think that fact that it's not choosing {0,0} by default means that y=0 is being brought into range by PlotRangePadding. So that may be another option to keep an eye on.) A: Here is (IMO) more elegant method based on belisarius's code which uses the DisplayFunction option (see here interesting discussion on this option): Plot[Evaluate[Table[BesselJ[n, x], {n, 4}]], {x, 0, 10}, Filling -> Axis, DisplayFunction -> Function[{plot}, Show[plot, AxesOrigin -> First /@ (PlotRange /. AbsoluteOptions[plot, PlotRange]), DisplayFunction -> Identity]]] The only drawback of both methods is that AbsoluteOptions does not always give correct value of PlotRange. The solution is to use the Ticks hack (which gives the complete PlotRange with explicit value of PlotRangePadding added): completePlotRange[plot_] := Last@Last@ Reap[Rasterize[ Show[plot, Ticks -> (Sow[{##}] &), DisplayFunction -> Identity], ImageResolution -> 1]] Plot[Evaluate[Table[BesselJ[n, x], {n, 4}]], {x, 0, 10}, Filling -> Axis, DisplayFunction -> Function[{plot}, Show[plot, AxesOrigin -> First /@ completePlotRange[plot], DisplayFunction -> Identity]]] It is interesting to note that this code gives exactly the same rendering as simply specifying Frame -> {{Automatic, None}, {Automatic, None}}, Axes -> False: pl1 = Plot[Evaluate[Table[BesselJ[n, x], {n, 4}]], {x, 0, 10}, Filling -> Axis, DisplayFunction -> Function[{plot}, Show[plot, AxesOrigin -> First /@ completePlotRange[plot], DisplayFunction -> Identity]]]; pl2 = Plot[Evaluate[Table[BesselJ[n, x], {n, 4}]], {x, 0, 10}, Filling -> Axis, Frame -> {{Automatic, None}, {Automatic, None}}, Axes -> False]; Rasterize[pl1] == Rasterize[pl1] => True
{ "language": "en", "url": "https://stackoverflow.com/questions/7616003", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: JQuery autoSuggest Plugin usage with asp.net mvc I've been trying to use this plugin -> http://code.drewwilson.com/entry/autosuggest-jquery-plugin (broken link, see github), but i've been having some problems. Here's what my view looks like. <span> <label for="registrars">Registrar</label> <input id="registrars" type="text" name="registrars" /> </span> <script type="text/javascript"> $(function () { var data = { items: @Html.Action("GetRegistrars", new { area = "Registrar", controller = "Home", organizationId = "0007511"}) }; $("#registrars").autoSuggest(data.items, { selectedItemProp: "name", searchObjProps: "name" }); }); </script> Here's my controller [HttpGet] public ActionResult GetRegistrars(string organizationId) { var registrars = _registrationService.GetRegistrarBy(r => r.Id== organizationId) .Select(s => new { id = s.ID, name = s.Name }).ToList(); return new JsonResult { Data = registrars, JsonRequestBehavior = JsonRequestBehavior.AllowGet, ContentType = "application/json" }; } When I browse to the view this is contained on instead of seeing the page i see the raw html for the entire view. By the way when i browse to the url http://localhost/Registrar/Home/GetRegistrar?organizationId=0007511 here's what i get back. [{"id":"000641","name":"TELSER, KAREN L"},{"id":"001195","name":"ALLRED, NANCY J"},{"id":"001196","name":"ANDERSON, NANCY L"},{"id":"001197","name":"BRENNER, SUSAN RICH"},{"id":"001198","name":"BRUGGER, BETTY O"},{"id":"001200","name":"ELSASS, JUDITH W"}] Thanks for any help! A: I use it a little differently...This may work for you too. Instead of trying to render out all of the Registrars onto the page in an array and then getting the autosuggest work off that array, I pass it the URL to an action method that returns Json data.. In this example im using a Url Helper to build the Url, but you could just hard code it if you want. $(document).ready(function () { $("#autosuggest").autoSuggest( "@Url.Blogging().Posts().FindCategories()", { minChars: 2, selectedItemProp: "name", searchObjProps: "name", asHtmlID: 'Categories' } ); }); Here is the JsonResult that brings back the data. public JsonResult FindCategories(string q) { var results = Services.Post.FindCategories(q); var model = Mapper.Map<IEnumerable<Category>, IEnumerable<AutoSuggestViewModel>>(results); return Json(model, JsonRequestBehavior.AllowGet); } Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616010", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: any way to make a progress bar that when the value is 0, it's 100%? I'm working on a debt tracking app, and have need for a progress bar that as the current debt goes down, the progress goes up. The only way I can think to do this would be to fudge the numbers around so that the progress bar MAX is set to 0, and then change the starting debt to be a negitive number, as follows ProgressBar.setMax(0); Integer startingdebt = -1000; // 1000$ owed ProgressBar.setProgress(currentlyowed); //say, -500 so you start with -1000, and add 500$ to it if you paid it. I don't know if this would work though, because I'm sure the progressbar control has a set minimum of 0 already, so you can't set max the same...is there a way to do this? Edit: Thanks for the answers guys, but I found an easier way: to share with others, here's my final code block: double startingamount = (this.c.getDouble(this.c.getColumnIndex(DbAdapter.KEY_STARTINGAMOUNT))); double currentamount = (this.c.getDouble(this.c.getColumnIndex(DbAdapter.KEY_CURRENTAMOUNT))); currentdebt.setText(formatter.format(currentamount)); double progresspaid = new Double(startingamount-currentamount); double progresspercentage = new Double((progresspaid / startingamount)*100); int progresspercent = (int)progresspercentage; progressbar.setText(Integer.toString(progresspercent)+"%"); progressbar.setMax(100); progressbar.setProgress(progresspercent); the key was to get a variable that subtracts the current amount from the starting amount, and then divides that by the starting amount. double progresspaid = new Double(startingamount-currentamount); double progresspercentage = new Double((progresspaid / startingamount)*100); Thanks again though, I really appreciate people helping me learn Java and android development, I'm a VB.net developer so some of this is still foreign to me. A: While this may not be ideal (I don't use Android and avoid UI coding ;-), the numbers and percentages can be calculated with a little math -- it may be problematic if the raw value is itself displayed on the progress bar. The percent going from 0 ... 100 is: percent = (current - min) / (max - min) (When min = 0, this is trivially percent = current / max.) And the percent going from 100 to 0 is: percentReverse = 100 - percent or, expanded: percentReverse = 100 - ((current - min) / (max - min)) Example, current = -800, max = 0, min = -1000: percent = (-800 - -1000) / (0 - -1000) = 200/1000 = 20 (% done) percentReverse = 100 - 20 = 80 (% left) Another example, current = 0, max = 2000, min = -1000: percent = (0 - -1000) / (2000 - -1000) = 1000/3000 = 33 (% done) percentReverse = 100 - 33 = 66 (% left) Happy coding. A: It's probably easiest just to track the debt as a positive integer and subtract the payments, but in case you have to keep it negative, maybe try something like this: // initialize int startingDebt = -1000; int currentlyOwed = startingDebt; ProgressBar.setMax(-startingDebt); // make a payment int payment = 500; currentlyOwed += payment ProgressBar.setProgress(-currentlyOwed);
{ "language": "en", "url": "https://stackoverflow.com/questions/7616016", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Windows Phone - Styles.xaml + Mango Conversion I had an application build with the Windows Phone 7.0 SDK. I now need to update that application to the Windows Phone 7.1 SDK. When I migrated the application, the background of all of my pages were changed to black. However, they were all White (as intended) when I used the 7.0 SDK. How do I fix this? With the 7.0 SDK all of my pages were defined as: <Grid x:Name="LayoutRoot" Background="{StaticResource PhoneBackgroundBrush}"> ... </Grid> The PhoneBackgroundBrush is defined in Styles.xaml. This file has the following: <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:System="clr-namespace:System;assembly=mscorlib"> <Color x:Key="PhoneBackgroundColor">#FFFFFFFF</Color> <SolidColorBrush x:Key="PhoneBackgroundBrush" Color="{StaticResource PhoneBackgroundColor}"/> </ResourceDictionary> Styles.xaml is referenced in App.xaml as shown here: <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="Resources/Styles.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> What is wrong? How do I get my background back to being White? A: See this article: Overriding themes in Windows Phone 7.5 (Mango) (Scroll down for the Mango parts) In short: You can't override the inherited XAML styles anymore. You have to override them in C# code, such as (App.Current.Resources["PhoneBackgroundBrush"] as SolidColorBrush).Color = Colors.White;
{ "language": "en", "url": "https://stackoverflow.com/questions/7616017", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Coldfusion Component Pointers I'm having an issue with a Coldfusion component that I'm building. Well, I'm not really sure if it's a problem or how things are supposed work, but it seems strange. First, I set up arguments for the init function of my component and invoke the component. But if I change one of the arguments after I invoke, it also changes the values held in the component. Is this correct? I'm not sure if I'm explaining this very well. Here's some pseudo-code: <cfset fruit = [] /> <cfset fruit[1] = { id = 1, name = "apple" } /> <cfset fruit[2] = { id = 2, name = "orange" } /> <cfset args = { title = "Fruit", data = fruit } /> <cfinvoke component="test" method="init" returnvariable="test" argumentcollection=#args# /> <cfset fruit[2].name = "banana" /> The init function stores the title and data arguments in the component's variables scope. Now, if I output the data from the test object, I get apple and banana. But I was expecting the component to retain the data that it received during the invoke. Let me know if I need to clarify anything. Thanks for any help! A: I'm not really sure if it's a problem or how things are supposed work, Yes, that is how your current code is supposed to work. Whether that is how you want it to behave is a different question .. Most complex objects (structures, components, etectera) are passed by reference. Meaning you are essentially just storing a pointer to the object, not the actual values. So you will always see any changes made to the underlying object. That is why the output from test changes. Arrays are an exception. They are usually (though not always) passed by value. Meaning you have an independent copy that will not reflect any changes made to the original object. Your example is interesting because it contains both. Changes to your nested structures (name=orange => name=banana) are visible in the component because the structures are passed by reference. But the parent array is not. So you could clear fruit and it would have no effect on the component. Example: <cfset fruit[2].name = "bananna" /> <!--- both dumps will show "bananna" ---> <cfdump var="#fruit#" label="Fruit Before" /> <cfdump var="#test.getDataArray()#" label="Test.Data Before" /> <cfset arrayClear(fruit) /> <!--- fruit is empty and the component array is not ---> <cfdump var="#fruit#" label="Fruit After" /> <cfdump var="#test.getDataArray()#" label="Test.Data After" /> Test: <cfcomponent> <cffunction name="init" returntype="any" ...> <cfargument name="title" type="string" required="true" /> <cfargument name="data" type="array" required="true" /> <cfset variables.title = arguments.title /> <cfset variables.data = arguments.data /> <cfreturn this /> </cffunction> <cffunction name="getDataArray" returntype="array"> <cfreturn variables.data /> </cffunction> </cfcomponent> Now, if I output the data from the test object, I get apple and banana. Right. That is to be expected because structures are passed by reference. If you want the component to maintain a independent copy, you need to duplicate() (ie deep copy) the data element inside init(). <cfset variables.data = duplicate(arguments.data) /> A: While Arrays are passed by VALUE in ColdFusion, even the objects inside them. If you want to retain the values in the function return the array that your init function updates and set your fruit array equal to that. I'd have a getter function that returned your array: <cffunction name="getArray" returntype="array" access="public" output="false" hint="return the array" > <cfreturn variables.theArray> </cffunction> And in your cfm template you'd set your fruit array equal to that value: <cfset fruit = test.getArray()>
{ "language": "en", "url": "https://stackoverflow.com/questions/7616020", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android App Architecture: how to share behavior between all screens Hi fellow Android coders, that's a problem I struggle with every time when I make a new app. Imagine you have sub classes of Activity, ListActivity and MapActivity in your app. Now I want that every screen has the same options menu showing up when the user clicks the menu button. So I made a BaseActivity with that behavior. But because Java doesn't allow multiple inheritance I have to write three BaseActivities for every type of Activity. That is ugly because I have three times the same code... The only solution I can think of is make some of the behavior static in one of those BaseActivities and refer to that in the other BaseActivites. But there are still a lot of duplicates... Anyone has a more elegant solution for that problem? Cheers A: This is one of the trade-offs for a single-inheritance language. Rather than duplicating code through inheriting various Activity sub-classes use a delegate. This is also called inheritance by delegation. You will get the features of multiple inheritance without the liabilities. This is a accomplished by creating a delegate class that has all the shared functionality you'd like then having the "super" class call the delegate. This will still require a small level of copy-and-paste code but it will be minimal. Wikipedia has a good example of the Delegation pattern. If you have a background in C# this form of delegation is similar but not restricted to single methods and for more than events.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616025", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: MVC3 Content->Site.css Where can I find some templates Are there any templates to replace site.css without having to change to HTML markup of the default _layout in MVC 3? A: There's the MvcContrib Template Gallery with a growing list of templates you can apply to your default mvc applications
{ "language": "en", "url": "https://stackoverflow.com/questions/7616041", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there example of scala abstract type usage which is impossible to achieve with generics? There are two possible way to express abstraction over types. abstract class Buffer { type T val element: T } rather that generics, e.g. abstract class Buffer[T] { val element: T } I understand benefits in usability of using different approaches in different contexts. But I'm interest in examples where it is absolutely impossible to convert Abstract Type version to Generic version. PS Code snippets are welcome. A: Another difference: only type parameters can be used as self-types, abstract class Buffer[T] { self: T => val element: T } A: // This is possible trait M { type TM } trait P[TP] extends M { type TM = TP } // This is not trait P[TP] trait M extends P[TM] { type TM } A: Abstract types can be bound to path dependent types which is not possible with type parameters. Thus you can e.g. implement an abstract type with a concrete inner class: trait A { type T } class B extends A { class T } or explicitly bind it to a path dependent type inside the classes scope: class C { type T = this.type } class D { object Q; type T = Q.type }
{ "language": "en", "url": "https://stackoverflow.com/questions/7616042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Permissions mode for child apps in current 3.x facebook-phpsdk I have been reading the facebook dev documentation as well as previous iterations of the php sdk. the old sdks had a 'permissions' mode for child apps [begin_permissions_mode(), end_permissions_mode()], but i see no references for a similar mode in the current 3.x php sdk. Does this functionality still exist?
{ "language": "en", "url": "https://stackoverflow.com/questions/7616044", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Query results showing rows as columns I have a form that dynamically creates checkboxes. The user signs in and selects 0 to all the checkboxes. The checkbox array is generated from the table 'options'. The form submit records into 2 tables 'survey' (one record of person data) and 'selections' (the survey key and the options key (or keys)). I want to pull out a report that will show all of the possible options as column headings with a list of people from the survey table who selected that option. So my result would look like this: FirstAid Triage Firefighting HamRadio Sam Sue Sam Judy Judy Bill Bob So all of the options show on the results, even if no one has selected it. Structure of the tables are: OPTIONS option_id description SURVEY survey_id name SELECTED OPTIONS survey_id option_id This is a simplified example of the actual data, but includes the critical pieces (I think). How can I use SQL to get the results I need? Thanks A: Disclaimer: I have not used Postgres in several years so there may be better methods of accomplishing this task than the ones that I list. Option 1: Use Case When statements as was done in the below linked solution. correct way to create a pivot table in postgresql using CASE WHEN Option 2: Use the Crosstab function available in the tablefunc contrib as was done in the below linked solution. PostgreSQL Crosstab Query Documentation for crosstab tablefunc contrib http://www.postgresql.org/docs/9.1/static/tablefunc.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7616045", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP - Simple IF ... ELSE IF... producing unexpected results, educate me? I am having trouble with a simple peice of php code. I am working with 2 product pricing tiers. These are based on whether a user has logged in, or not. If a user is not logged in, and the first price is empty; then the price is price1. If not, it is price1. This works perfectly fine. If a user is logged in, and the first price is empty; then the price is price1. If not, it is price2. This is the way it should work, but what actually happens is this: If a user is logged in, and the first price is empty; then the price is 0. If not, it is price2. Why is my code producing this effect? if (!userIsLoggedIn()) { if (empty($prPrice2)) { $prPrice = $prPrice1; } else { $prPrice = $prPrice1; } } else if (userIsLoggedIn()) { if (empty($prPrice2)) { $prPrice = $prPrice1; } else { $prPrice = $prPrice2; } } else { $prPrice = $prPrice1; } If anyone has any suggestions that could help me to resolve this issue, it would be greatly appreciated. Thank you! @Pekka, it is fairly complicated. I simply would like this to happen: product 1 -> price 1 = 1.00 product 1 -> price 2 = 0.00 product 2 -> price 1 = 1.00 product 2 -> price 2 = 0.80 If a user is logged in but the price2 field is empty, then the price variable will be price1. if not, then it will be price 2. On the other hand, if a user is not logged in but the price2 field is empty, then the price variable will be price1. if not, then it will be price 1. A: The way you explained the rules was a bit confusing. You should be able to modify the below code to fit: if (userIsLoggedIn()) { $prPrice = !empty($prPrice2) ? $prPrice2 : $prPrice1; } else { $prPrice = !empty($prPrice1) ? $prPrice1 : $prPrice2; } A: The code is in contradiction with the algorithm you described. You told: If a user is not logged in and the first price is empty, then the price is price1. If not, it is price2. If a user is logged in and the first price is empty, then the price is price1. If not, it is price2. So, in fact, the algorithm should do exactly the same thing whether the user is logged in or not. In your code, it's also very strange: You have three conditions: * *user is not logged in *user is logged in *other The user is logged in or it's not logged in. I don't see any other possibility. And also, the following lines: if (empty($prPrice2)) { $prPrice = $prPrice1; } else { $prPrice = $prPrice1; } could be reduced to $prPrice = $prPrice1; since you're doing the same operation in the two code blocks. A: You code is overly complicated and contains some odd constructions. This is an equivalent but simplified version, but check the comment I added on the first else.... if (!userIsLoggedIn()) { if (empty($prPrice2)) { $prPrice = $prPrice1; } else { $prPrice = $prPrice1; // this is highly suspicious... } } else { // user is logged or not, no need to recheck that boolean var if (empty($prPrice2)) { $prPrice = $prPrice1; } else { $prPrice = $prPrice2; } } a slightly fancier way of expressing the same condition with the ternary statement (example is equivalent to else block of the outer if: $prPrice = (empty($prPrice2)) ? $prPrice1 : $prPrice2; EDIT Assuming that there is a way to differentiate between accountholders that haven't logged in and users without accounts, your need to handle that in an outer condition, like this: if ($UserHasAnAccount) { // but i don't understand (yet) how you'd know that at this point if (userIsLoggedIn()) { // the price logic described before .... } else { .... } } else { // unknown user, price1 $prPrice = $prPrice1; } A: else { $prPrice = $prPrice1; } You can't reach this condition because as I understand userIsLoggedIn is boolean and it may happen only two conditions: when userIsLoggedIn is true and when it false. You wrote that If a user is not logged in and the first price is empty, then the price is price1. If not, it is price2. But in you code this happens: If a user is not logged in and the second price is empty, then the price is price1. If not, it is price1 too. Also in the condition userIsLoggedIn you wrote that If a user is logged in and the first price is empty But in your code you check if the second price is empty.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616047", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: WCF and XmlSerialization and XmlWriterSettings I have a REStful WCF web service (using a substantially modified WCF Rest Starter Kit) and the data contracts are simple POCOs marked with [Serializable] and [XmlType] (with members tagged with [XmlElement] or [XmlAttribute] where appropriate). Somewhere inside WCF an instance of XmlSerializer is created which generates the output with no indentation or spacing between XML nodes, which is fine for automated processes, but makes debugging harder as I have to manually format the XML output myself. I want to use XmlWriterSettings so it will automatically format the XML before it gets sent down the pipe, but I can't see where I could inject it. I used Reflector to find where XmlSerializer is instantiated within WCF and it shows up inside a few nested internal classes isnide XmlSerializerOperationBehavior, but beyond that I'm stuck. Ta! A: The XmlWriterSettings object isn't passed to the constructor to the XmlSerializer, but to the XmlWriter which will be then passed to the serializer when it's time to write the object out. The place where you can change that is a custom message encoder (responsible for converting between the XML Infoset in the message and the actual bytes in the wire). One good sample of a custom encoder which creates a XmlWriter instance is the "Custom Text Encoder". A: I think you can control the complete XMLSerializer output that WCF uses to create the message transcription. Hints and examples are given in http://msdn.microsoft.com/en-us/magazine/cc163569.aspx.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C++ Strong Random Number Generator - necessary? My newest project is the development of a text based RPG and now I need a random number generator, a good one to compute in different situations whether some action can be performed without problems or not. Everyone of us knows, that the basic functions std::srand and std::rand are simple and easy algorithms to compute pseudo random values. However I want to have real and not pseudo values. Therefore i want to ask, whether it would to much overkill using a better solution than the mentioned one and to stick to the basics; and if not, what would you suggest? How to implement such a "good generator"? A: My suggestion is to use Boost.Random. It has a number of quite good (and fast) RNGs. You don't need a cryptographically secure one, but the ones they offer are better than rand. I'd go with mt19937 myself. It has a long period and is pretty fast. But Boost.Random has lots of these things, for most of your non-cryptographically secure needs. A: The real question is... will anyone know the difference between your pseudo and real random numbers? I don't think anyone will. The libraries you find by default are sound enough that your users will never be able to find any patterns. A: Maybe you are confused about several distinct concepts. One concept is unpredictability: Since a PRGN is based on deterministic algorithms and a single seed value, it is possible to predict the next "random" number based on observations of previous numbers. This is a huge problem in cryptography, so to avoid this, you would pick a "true" random number from some genuine entropy source such as /dev/random. However, this is only useful for one single random number. The other concept is that of a probability distribution. If you want numbers uniformly distributed over an interval, you need a method to achieve this correctly, or your random events will come out as skewed. This isn't related to unpredictability, and a rather predictable pseudo-RNG may be entirely suitable for producing a statistically correct uniform (or any derived) distribution. Since your game mechanics will almost surely depend on good statistical properties of the random events, you should focus primarily on picking a good pseudo-RNG, and then seed this from a sufficiently random source (maybe /dev/random). True randomness is no good in a game where you need control over the statistical properties of random events. A: From personal experience, it depends how you're accessing the random numbers. If you're generating many random numbers one after the other in very quick succession, then chances are you'll want something more complex (e.g. creating a large vector of random values). For a typical RPG game however, the standard RNGs should be fine. A: Since computers are deterministic, any random number generator is pseudo random. However, some algorithms are better than others. For a game, the built in std::rand functions more than enough. The only real applications for more complex random number generators is encryption. A: First of all, every random number generator implemented in software is pseudo-random, you would need to rely on some physical phenomena (like radioactive decay) to get guaranteed (by modern physics) randomness. But in most applications (I'm not familiar with your) randomness of computationally simple pseudo-random generators is quite acceptable. There were a number of those facilities added in TR1, no need to reinvent the wheel, just check this article: Random number generation using C++ TR1 A: In linux, /dev/random is a good solution. For real random values, you can't use just a program. Software is unable to generate true random values. But true randomness is hardly ever needed. Could you be more specific what you need the random numbers for?
{ "language": "en", "url": "https://stackoverflow.com/questions/7616062", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I get the left and right arrow keys to work with jQuery? How do I get the left and right arrow keys to work in this situation using jQuery? $(document).ready(function() { $('#container').click(function() { var totalWidth = 0; var sizeWidth = $('#insertData1').outerWidth(); $('#ul_a li').each(function() { var widthS = $(this).width(); var textW = $(this).text(); var widthN = parseInt(widthS,10); if((totalWidth + widthN) < sizeWidth) { totalWidth = totalWidth + widthN; $('#ul_b').append('<li>' + textW + '</li>'); } else { return false; } }); $('#ul_b li').hover(function() { $(this).addClass('highlight'); }, function() { $(this).removeClass('highlight'); }); $('#ul_b li').keypress(function(e) { if(e.which == 37) { $(this).removeClass('highlight'); $(this).prev().addClass('highlight'); } elseif(e.which == 39) { $(this).removeClass('highlight'); $(this).next().addClass('highlight'); } return false; }); }); }); By the way, even tried using keyup and get the same problem... $('#ul_b li').keyup(function(e) { if(e.keyCode == 37) { $(this).removeClass('highlight'); $(this).prev().addClass('highlight'); } elseif(e.keyCode == 39) { $(this).removeClass('highlight'); $(this).next().addClass('highlight'); } return false; }); A: Use keydown or keyup. The Keypress event listener doesn't recognise non-character keys (the key code of the arrow keys at keypress are zero). Coincidentally, I've just written an arrow key script for another question. See this Fiddle for an example of the key code script: http://jsfiddle.net/ATUEx/ (Question) Note: I've found (and fixed) another error: elseif is not a valid JavaScript expression. Use else if (with a space in between else and if) instead. Your fixed code: $(document).ready(function() { $('#container').click(function() { var totalWidth = 0; var sizeWidth = $('#insertData1').outerWidth(); $('#ul_a li').each(function() { var widthS = $(this).width(); var textW = $(this).text(); var widthN = parseInt(widthS,10); if((totalWidth + widthN) < sizeWidth) { totalWidth = totalWidth + widthN; $('#ul_b').append('<li>' + textW + '</li>'); } else { return false; } }); $('#ul_b li').hover(function() { $(this).addClass('highlight'); }, function() { $(this).removeClass('highlight'); }); $('#ul_b li').keydown(function(e) { if(e.which == 37) { $(this).removeClass('highlight'); $(this).prev().addClass('highlight'); } else if(e.which == 39) { $(this).removeClass('highlight'); $(this).next().addClass('highlight'); } return false; }); }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7616069", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: class appears to be missing from the org.eclipse.OSGI jar? I received a new program which I am trying to run. It uses OSGI and is returning a clasnotfoundexception when it tries to access org.eclipse.osgi.framework.internal.core.OSGi. I'm trying to figure out where this class should be located. The package came with a jar file named org.eclipse.OSGI.jar (no version numbers). I checked this jar and it contains the org.eclipse.osgi.framework.internal.core package; but not an OSGi class within it. I checked the old jar that came packaged with an earlier version of the same application (org.eclipse.OSGI_3.5.1) and it doesn't have the OSGi class either. I tried looking online and I was able to determine that the older org.eclipse.OSGI_3.3 jar had the OSGi class, but otherwise found no allusion to it. So can someone clear up my confusion. Is this class suppose to be part of my 3.5 jar and I'm just too blind to find it, is it part of an entirely different jar, or has it been removed entirely? A: That is an old launcher class that has been replaced. You should consult the Main-Class manifest header in your org.eclipse.osgi.jar.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616072", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a way to do this check without two if statements in PHP? i have this if statement if(file_exists( $_SERVER{'DOCUMENT_ROOT'}.$writabledir.$name) && filemtime($_SERVER{'DOCUMENT_ROOT'}.$writabledir.$name) < $olddate) { if the file is there all is well but if the file is not there I get this error Warning: filemtime(): stat failed for /User.... I know I can do an if and then an inner if but is there a better way? A: If file_exists is returning false, then the filemtime call should never happen. && is a short-circuiting logical AND in PHP, meaning that if it doesn't need to make the second call (i.e. first part of the logical statement is false, therefore there is no way the whole statement could be true), it won't. There might be something else weird going on in your code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616073", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: datePicker crashes after multiple selections Im having a heck of a time. I have a datePicker setting start and end dates, like the apple calendar. I am crashing with no messages whenever I click the datePicker multiple times. I'm guessing Im leaking memory but cannot find it. please help... ecause I need to access these in multiple methods, I made my UIDatePicker and NSDateFormatter into ivars. the BOOL's are set when buttons are pressed and everything is set up to accept multiple touches in IB. works fine if the datePicker is only clicked once or sometimes twice. .h IBOutlet UIDatePicker *datePicker; NSDateFormatter *dateFormatter; NSDateFormatter *timeFormatter; @property (nonatomic, retain) UIDatePicker *datePicker; @property (nonatomic, retain) NSDateFormatter *dateFormatter; @property (nonatomic, retain) NSDateFormatter *timeFormatter; .m @synthesize datePicker; @synthesize dateFormatter, timeFormatter; viewDidLoad: NSDate *now = [[NSDate alloc] init]; [datePicker setDate:now animated:NO]; //known bug - hopefully fixed in 4.3 //[datePicker setMinimumDate:now]; [now release]; self.dateFormatter = [[NSDateFormatter alloc] init]; [self.dateFormatter setDateStyle:NSDateFormatterMediumStyle]; [self.dateFormatter setTimeStyle:NSDateFormatterNoStyle]; formattedDateStringDate = [self.dateFormatter stringFromDate:datePicker.date]; NSLog(@"initdate %@", formattedDateStringDate); self.timeFormatter = [[NSDateFormatter alloc] init]; [self.timeFormatter setDateStyle:NSDateFormatterNoStyle]; [self.timeFormatter setTimeStyle:NSDateFormatterShortStyle]; formattedDateStringTime = [self.timeFormatter stringFromDate:datePicker.date]; NSLog(@"initTime %@", formattedDateStringTime); valueDidChange: - (IBAction)changeDateInLabel:(id)sender { formattedDateStringDate = [dateFormatter stringFromDate:datePicker.date]; //NSLog(@"date %@", formattedDateStringDate); formattedDateStringTime = [timeFormatter stringFromDate:datePicker.date]; //NSLog(@"time %@", formattedDateStringTime); if (isStartDateSet) { startDateLabel.text = formattedDateStringDate; startTimeLabel.text = formattedDateStringTime; newDate = formattedDateStringDate; newStartTime = formattedDateStringTime; } if (isEndDateSet) { endTimeLabel.text = formattedDateStringTime; newEndTime = formattedDateStringTime; } } all three set to nil in viewDidUnload and all three released in dealloc. A: You need to change some things before further investigation: * *self.dateFormatter = [[NSDateFormatter alloc] init]; After this the dateFormatter's retain count is 2, 1 for the alloc and 1 for the property 'retain'. Change it to just dateFormatter = [[NSDateFormatter alloc] init]; Same for the timeFormatter and probably the datePicker too. * *After setting a member to nil, you cannot release it anymore. Do it the other way round.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616081", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to Migrate from Hibernate Validator Legacy (3.x) to Hibernate Validator 4.x Our application was built using Hibernate Validator 3.1.0 (now called Hibernate Validator Legacy). I'd like to migrate it to use Hibernate Validator 4.x (4.2.0). I can't seem to find any documentation on the approach to migrating an application from using 3.x to 4.x. It's mentioned in certain places, but I can't find any useful information whatsoever. It's as if the creators of 4.x just left everyone on 3.x dangling. Can anyone provide some useful information or links on the process. Thanks. A: Situation is still more or less as you described. Best available document seems to be JBOSS AS migration document, and that is not much.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616083", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Testing jquery dialog with capybara-webkit I want to test an interaction where the user clicks a link and a jquery dialog (http://jqueryui.com/demos/dialog/) pops up. I would like to test: * *That the dialog shows up *That text in the dialog box is correct *That the user can exit by clicking the 'x' I tested the dialog manually and it works but I am interested in how I would write the actual spec. I would like to do this using Capybara-webkit, but I haven't been able to find code samples for actually using Capybara-webkit. I am using Capybara-webkit and specs but not cucumber. A: Here's how to do this: Resources * *Railscasts Episode 257: Request Specs and Capybara *Capybara-webkit on Github Installation Make sure your Gemfile includes capybara-webkit, rspec-rails, and database_cleaner: group :development, :test do gem 'rspec-rails', '~> 2.7.0' gem 'capybara-webkit', '~> 0.7.2' gem 'database_cleaner', '~> 0.6.7' end You need database_cleaner because database transactions aren’t compatible with rspec drivers besides Rack::Test: RSpec.configure do |config| #... config.use_transactional_fixtures = false config.before(:suite) do DatabaseCleaner.strategy = :truncation end config.before(:each) do DatabaseCleaner.start end config.after(:each) do DatabaseCleaner.clean end end You must still use the :js => true flag in your tests. Turns out, it's not a selenium-only feature: describe "Something" do it "uses javascript", :js => true do pending "write a test" end end And, of course, require 'capybara/rspec' and set Capybara.javascript_driver = :webkit in your spec_helper: #... ENV["RAILS_ENV"] ||= 'test' require File.expand_path("../../config/environment", __FILE__) require 'rspec/rails' require 'capybara/rspec' Capybara.javascript_driver = :webkit #... That should be all it takes to get capybara-webkit and rspec up and running.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616095", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to render new.js.coffee.erb in app/views? Using Rails 3.1 jquery_ujs, I have a link with :remote => true, and the controller new action responds with js and render new.js.erb which contains: $('#post-form').html('<%= escape_javascript(render(:partial => "form")) %>'); It renders the _form.html.erb partial. This works. Now I want to use Coffeescript, but renaming new.js.erb to new.js.coffee.erb doesn't work. Does the asset pipeline only work in app/assets? What am I doing wrong? Thanks. A: I had this same issue using Rails 3.1.0. Try renaming your file to just new.js.coffee. It should still render erb despite not having the extension on the filename. It's definitely confusing that view templates don't follow the same conventions as the asset pipeline. A: If you wish to keep the .js.coffee.erb extension here's a piece of code for Rails 4 to have Rails recognize the file as a valid view template: # config/initializers/coffee_erb_handler.rb ActionView::Template.register_template_handler 'coffee.erb', Coffee::Rails::TemplateHandler # without this there will be template not found error class ActionView::PathResolver < ActionView::Resolver EXTRACT_METHODS = %w{extract_handler_and_format_and_variant extract_handler_and_format} # name for rails 4.1 resp. 4.0 method_name = EXTRACT_METHODS.detect{|m| method_defined?(m) || private_method_defined?(m)} raise 'unknown extract method name' if method_name.nil? old_method_name = "old_#{method_name}" alias_method old_method_name, method_name define_method(method_name) do |path, default_formats| self.send(old_method_name, path.gsub(/\.js\.coffee\.erb$/, '.js.coffee'), default_formats) end end (This is a contribution by cervinka on coffee-rails issue #36)
{ "language": "en", "url": "https://stackoverflow.com/questions/7616097", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "31" }
Q: How do I use max() in sql I have a table that looks like this: col1 col2 col3 ------ ----- ----- A 1 trout A 2 trout B 1 bass C 1 carp C 2 tuna D 1 salmon I really only want to select the rows with the max value for col2. The query I want to generate would return the following: col1 col2 col3 ------ ----- ----- A 2 trout B 1 bass C 2 tuna D 1 salmon I've tried something like this: select col1, max (col2) as mCol2, col3 from mytable group by col1, col2 In this case I get: col1 Mcol2 col3 ------ ----- ----- A 2 trout B 1 bass C 1 carp C 2 tuna D 1 salmon As you can see, I still get C, 1, carp, when I'm only wanting C, 2, tuna. I've considered trying to do something like select col1, col2, col3 from mytable where col1-n-col2 in ( select col1, max (col2) as mCol2 from mytable) group by col1, col2 But I don't think that's legal in SQL. What obvious solution have I missed? A: If (col1, col2) is unique, or if you don't mind duplicates in the case of ties: SELECT T1.col1, T1.col2, T1.col3 FROM mytable T1 JOIN ( SELECT col1, MAX (col2) AS mCol2 FROM mytable GROUP BY col1 ) T2 ON T1.col1 = T2.col1 AND T1.col2 = T2.mCol2 If you want to choose any row in the case of a tie (requires ROW_NUMBER support, i.e. not MySQL): SELECT col1, col2, col3 FROM ( SELECT col1, col2, col3, ROW_NUMBER() OVER (PARTITION BY col1 ORDER BY col2 DESC) AS rn FROM mytable ) T1 WHERE rn = 1 A: Analytic functions are by far the best way to solve this sort of problem as they will perform much better than a sub query over a large data set. Either try the second query provided by Mark Byers or try the query shown below: select col1, max (col2) as mCol2, max (col3) keep (dense_rank last order by col2) as col3 from mytable group by col1 This uses the LAST analytic function to get the last value in each group after ordering by col2. The MAX used for col3 is required by the syntax but is only really a tie-breaker. A: you were close select t.col1, t.col2, t.col3 from mytable t, (select col1, max (col2) as mx from mytable group by col1) m where m.col1 = t.col1 and m.mx = t.col2 A: You didn't specify which database you're using - on SQL Server and a few others, you could use a CTE (Common Table Expression) with a windowing function to get your rows: ;WITH HighestOnly AS ( SELECT col1, col2, col3, ROW_NUMBER() OVER(PARTITION BY col1 ORDER BY col2 DESC) AS 'RowNum' FROM MyTable ) SELECT col1, col2, col3 FROM HighestOnly WHERE RowNum = 1 This will "partition" your data by the criteria specified (col1) and dish out consecutive numbers for each data partition, starting at one - ordered by a second criteria given (col2 DESC). So for each "partition" of data, the row with the highest value in col2 will have RowNum = 1 - and that's what I'm selecting here. A: Try select mytable.col1, mytable.col2, mytable.col3 from mytable join ( select col1, max(col2) as col2 from mytable group by col1) as mytablemax on mytable.col1 = mytablemax.col1 and mytable.col2 = mytablemax.col2 A: Here is one approach With max_qry as (select col1, max(col2) as mcol2 from mytable group by col1) select m.col1, m.col2, m.col3 from mytable m join max_qry on m.col1 = mq.col1 and m.col2 = mq.mcol2 A: hei.. I don't have an Oracle database installed but for MySQL this is wrong.. It is because of your space in syntax... the correct version is SELECT MAX(column) ... and not SELECT MAX (column) ... I don't think that with space is recognized as a function...
{ "language": "en", "url": "https://stackoverflow.com/questions/7616103", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Passing parameters to the constructor to an object (Actionscript 3) I am working on a side-scrolling platformer game. Because of this, I have a class that acts as a floor. I also have a class representing enemies. I am having problems with passing a parameter to a custom class' constructor. The class (SkullDemon.as) extends MovieClip. I am trying to pass an instance (called "floorL1") of a customer class called "FloorLevel1." "FloorLevel1" also extends MovieClip (I do not have a written .as file for "FloorLevel1"; I just exported the floor MovieClip to that class). I am trying to pass an instance of "FloorLevel1" so that the "SkullDemon" object can land on the floor just like in a platformer. My main class is called "TME2_Main." This is the class from which I try to pass the "floorL1" instance to the "SkullDemon" class. This is how I try to create a Skull Demon instance and pass "floorL1" to its constructor: skullD1 = new SkullDemon(floorL1); I try to create the SkullDemon within "TME2_Main's" constructor. Here is the "SkullDemon" class' constructor : // Constructor (takes in Level 1's floor variable as an argument public function SkullDemon(floorL1:FloorLevel1) { //public function SkullDemon() { // Move the Skull Demon as soon as it is created moveSkullDemon(); } I get two types of errors when I run the .swf: ArgumentError: Error #1063: Argument count mismatch on SkullDemon(). Expected 1, got 0. at flash.display::Sprite/constructChildren() at flash.display::Sprite() at flash.display::MovieClip() at TME2d_Main() TypeError: Error #2007: Parameter child must be non-null. at flash.display::DisplayObjectContainer/addChild() at flash.display::Stage/addChild() at TME2d_Main() What am I doing wrong here? I have spent a while looking for solutions (including moving code outside of TME2_Main's constructor), but nothing has really helped me so far. A: Sounds like you have an instance of SkullDemon somewhere on the stage. If you do, Flash will attempt to call the constructor for SkullDemon without passing any arguments. You can usually tell this is the problem when it happens in the Sprite class's constructChildren() method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616110", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Parsing url inside string How would I go about matching the following string format ( everything after the equal sign to the end of the .html http%3A%2F%2Fwww.mydomains.com.com%2FSA100.html inside the string below: http://www.tticker.com/me0439-119?url=http%3A%2F%2Fwww.mydomains.com.com%2FSA100.html%3Fc%2acn%2CSA400 A: Simplest I could come up with was: /url=(http.*\.html)/ Use the capture group for your URL. A: (?<==).*?\.html test with grep kent$ echo "http://www.tticker.com/me0439-119?url=http%3A%2F%2Fwww.mydomains.com.com%2FSA100.html%3Fc%2acn%2CSA400"|grep -Po "(?<==).*?\.html" http%3A%2F%2Fwww.mydomains.com.com%2FSA100.html A: In perl: #!/usr/bin/perl -w use URI; my $uri = URI->new("http://www.tticker.com/me0439-119?url=http%3A%2F%2Fwww.mydomains.com.com%2FSA100.html%3Fc%2acn%2CSA400"); # create URI object my %params = $uri->query_form(); # get all params my $param_url = $params{url}; my $uri2 = URI->new($param_url); # create new URI object from param URL $uri2->query(undef); # strip parameters print $uri2->as_string(); gives: http://www.mydomains.com.com/SA100.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7616112", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jquery click event handler for items within a div How do you add a jquery click event handler for a bunch of links within a div? For example: <div class="test"> <a href="test1.html">link 1</a> <a href="test2.html">link 2</a> <a href="test3.html">link 3</a> </div> I'd like to add a click event handler for each of the three links, so I can addClass('selected') to the link that was clicked on and removeClass('selected') from the rest. I know I can do them one by one, but I was wondering what the cleanest way to do this is... A: I would use .delegate(): var classname = 'selected'; $('div.test').delegate('a', 'click', function () { $(this).addClass(classname).siblings().removeClass(classname); }); A: The selector will return an array of elements that match. $('div.test a') will be the tree links. $('div.test a').click(function() { }); Will bind to all three. A: Selectors work like CSS selectors, so this selects a tags inside tags with class test $('.test a').click(function(){ // select the object that was clicked on $(this) // add the selected class to it .addClass('selected') // remove the selected class from it's brothers and sisters .siblings().removeClass('selected') // stop link from loading and resetting page return false }) Demo here: http://jsfiddle.net/HK6CE/ A: I would write (with no extra markup): $('.test a').bind('click', function() { $(this).addClass('selected').siblings().removeClass('selected'); }); Siblings() gets all the others dom elements on the same level, so it'll get all the others "a" inside .test A: I believe it's $('.test').each(function(){})
{ "language": "en", "url": "https://stackoverflow.com/questions/7616113", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Android screen resolutions and density. Packages of images I have a problem in my android app: I have 4 packages of images (for 320x240, 800x480, 854x480 and 1024x600 resolutions). I want to have one layout which should look good for any resolution or density (of my 4 packages). Now if I set Padding Left 120 dip for example I have different offsets if different density. How to make offsets identical in appearance for any density? In which folder should I put my pictures so that my layout look good for any density screen? Also what should I write in manifest file for correct work of the app for any density? Please help!!! Thanks and sorry for my English... A: there are various possibilities to dynamically be ready to every screen size. what you should do, is add the different drawable directories. there are many different accepted directories that will dynamically use the correct images in the users device. try reading the adroids supporting different screen sizes article. good luck
{ "language": "en", "url": "https://stackoverflow.com/questions/7616115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Tutorials.exe windows services I create new project "Tutorials.exe"; when I run on cmd the path: C:\temp>installutil turorials.exe ...I get the error: 'installutil' is not recognized as an internal and external command,operable program or batch file. I tried another way: C:\Windows\Microsoft.NET\Framework\v4.0.30319>installutil Tutorials.exe ... I get the error: 'Tutorials.exe' is not recognized as an internal and external command,operable program or batch file. What is going on here? A: You almost figured out the problem, when you ran the first command, installutil wasn't found because the directory isn't in your path by default. I guess your Tutorials.exe is in c:\Temp. If so, run this command: C:\Windows\Microsoft.NET\Framework\v4.0.30319>installutil c:\Temp\Tutorials.exe A: Hi you need to determine what version of .NET framework which you use to build Tutorials.exe window service app. Then point to valid version .NET framework PATH of installutil.exe, finally run the command like skjaidev has told
{ "language": "en", "url": "https://stackoverflow.com/questions/7616117", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Auto-arrange UML diagrams in visual studio 2010 I'm creating UML diagrams (use case and class diagrams) in Visual Studio 2010 for a new project. Instead of using drag and drop to place all the model elements in a visually pleasing way, I would like to automatically arrange the diagrams, to save time. Is that possible in Visual Studio 2010 Ultimate? In other VS2010 editions? A: Depending on the kind of diagrams you are making, there is often a Rearrange layout icon enabled in the Modelling toolbar. Also, right click on the background of the diagram to be able to find and select that option. However, I'm not sure if you are going to be satisfied of the result of the auto-arrange capabilities of VS2010. For example, in the sequence diagram, click the layout icon left of Create Work Item: (this is not available in the Class diagram) Only the VS2010 Ultimate edition allows modelling projects, so that answers the second part of your question.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616126", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: MySQL / Searching Two Tables I have two tables, 'photos' and 'videos'. Together they are almost identical, except one column, 'photoID' in 'photos' and 'videoID' in 'videos'. When a user makes a search, I would like the video results to be mixed with the photo results, obviously from the same recordset. How is it possible to do this using different column names? If it's not, do I change the column names to something like contentID, in both tables, and use a UNION to join them? It's a lot of work changing the columns but will have to if this isn't possible... A: You don't have to change the column names in the tables. Just use an alias on the SELECT. I'd go with a UNION ALL (more efficient than UNION as it won't try to eliminate dupes) and add an additional column to identify where the content came from. SELECT photoID AS contentID, colA, colB, ..., 'photo' AS ContentType FROM photos UNION ALL SELECT videoID AS contentID, colA, colB, ..., 'video' AS ContentType FROM videos A: Select * from ( SELECT VideoID as MediaID, * FROM Videos UNION SELECT PhotoID as MediaID, * FROM Photos ) as T WHERE MediaID = ? A: use something similar to select photoID AS ContentID, col1, col2 FROM PHOTOS WHERE col1 =... UNION select videoID AS ContentID, col1, col2 FROM VIDEOS WHERE col1 =... A: select column1, column2, NULL videoID, photoID from photos where criteria = 'criteria' union all select column1, column2, videoID, NULL photoID from videos where criteria = 'criteria' A: If you are looking to make a union without displaying photoID and videoID, you can do it this way: SELECT column names from Videos UNION SELECT column names from Photos
{ "language": "en", "url": "https://stackoverflow.com/questions/7616127", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get SFML cross-platform typedefs in SWIG I'm writing an C++ game and I'm connecting it with Lua. The tool I chose for this task was SWIG, since I want to make my game available to be written in python or some other language. I'm also using SFML 1.6 as the API for multimedia access. This game is also intended to be cross-platform compilable. I'm working at the moment with Xubuntu 11.04 for the first try of the project. I've already wrapped 90%+ of the SFML API in my game, but when I tried to create an new sf::Color object in my Lua script (so that I could call an sf::RenderWindow::Clear(sf::Color) method), my Lua Script accused that this call ... renderWindow:Clear( sf.Color( 200, 0, 0 ) ) --Fill the screen with the color. ... tried to invoke method sf:Color( Uint8, Uint8, Uint8 ); This warning alerted me that SWIG could not identify the SFML special typedef integers for cross-platform development that are defined in the <SFML/Config.hpp> header file. Now, in my SWIG Config.i file I could simply write ... typedef unsigned char Uint8; //Always correct typedef unsigned short int Uint16; //Not always true typedef unsigned int Uint32; //Not always true ... and when compiling my project in another platform, I could just write these typedefs attending to this new platform, but I found out that c's limits.h header file contains some preprocessor defines for the size of each type of integer variable. My main purpose is to create these typedefs in my SWIG script without having to worry in which platform (or compiler) I'm compiling my project. Right now, my Config.i SWIG file looks like this: %{ #include <limits.h> #include <climits.h> #include <SFML/Config.hpp> %} %include <SFML/Config.hpp> And my SWIG command for generating the wrappers is: swig -c++ -lua -I/PathToSFML -I/PathToLimits ./SFML.i I was hoping that SWIG could find the preprocessor defined variables in the limits.h file, which is used by <SFML/Config.hpp> but I couldn't make this work... Does anyone have some tips on how to accomplish my goal ( dynamic typedefing for each platform ) or know a way to make swig get the preprocessor variables defined in limits.h? A: Any types defined in limits.h are not standard and probably shouldn't be relied on. If you want cross-platform fixed size integer typedefs, the C++11 standard library provides the cstdint header. This header gives you typedefs for signed and unsigned 8, 16, 32, and 64-bit integers: int32_t, uint32_t, int8_t, and so on. Most standard library implementations provided cstdint as an extension before C++11, but if your implementation doesn't have it, Boost also provides it. A: Thanks to user dauphic's answer, I tried to use <stdint.h> in my example, and then I got this error message when running SWIG in my module: /usr/include/stdint.h:44: Error: Syntax error in input(1). Searching on Google resulted to me these two web pages: * *[Perl] a simple typedef question #1 *[Perl] a simple typedef question #2 The second one gave me the answer to this. My final code looks like this right now: %module Config %include <stdint.i> //namespace sf // For some reason, not working when the namespace is here... //{ // Turns out that I don't need the sf anyway... typedef int8_t Int8; typedef uint8_t Uint8; typedef int16_t Int16; typedef uint16_t Uint16; typedef uint32_t Int32; typedef uint32_t Uint32; //} As you can see it, %include <stdint.i> is a pre-defined module in SWIG since version 1.34 (not really sure about the version... read it somewhere and forgot) which is ready to be used.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616132", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: mocking web service I would like to mock a web service call to test my code. The following is a code snippet of which I want to mock. I would like to test callWebService() method. I want a way to create my own HttpResponse when callRestClientService(criteria) is called. I tried using JMock and EasyMock but unable to get the desired result. At the first instance I believe that I will not be able to mock or create my own HttpResponse. Even if I am not able to mock the gateway call, I already have a local server to which I can make call to, but I would have to mock the reply sent back by the server to test different scenarios. Can anyone help me with this.... Thanks!! public class RestClientServiceResponse { public HttpResponse callRestClientService(final RestClientServiceCriteria criteria) throws IOException { final HttpUriRequest request = buildHttpUriRequest(criteria); return executeRestClientServiceCall(request); } public HttpResponse executeRestClientServiceCall(final HttpUriRequest request) throws IOException { final HttpClient client = new DefaultHttpClient(); final HttpResponse httpResponse = client.execute(request); return httpResponse; } } public class CallWebService { public void callWebService() { HttpResponse httpResponse = null; try { httpResponse = restClient.callRestClientService(criteria); } catch (final Exception e) { System.out.println(e); } } } A: If I understand you right, just use something like an embedded Jetty or Simple HTTP server. I tend to use Simple because it has generally better documentation. You can very easily set it to return whatever you want for a test. Depending on the complexity you need, you can even embed a mock inside the server, letting you perform normal mocking operations on the mock, which are translated into verifying HTTP requests and preparing HTTP responses. A: SoapUI is a open source tool created to test web services and it supports service mocking very well. Go through this tutorial on how to do it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616135", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cancel infinite loop execution in jsfiddle When you get an infinite loop in jsfiddle in Chrome, your only choice (that I know of) is to close the tab. Of course, this means you lose all your work in the current window! Is there an easy way to stop an infinitely executing script? * *I have the developer tools open because I was doing some debugging. *I am able to pause the script and step through the loop. *I can't find anywhere to stop the script. *I can't modify the script or variables to stop the infinite loop (because the script execution occurs in an iframe on a separate domain, so modifying data in the iframe with JavaScript is not allowed and generates an Exception in the console). It all started because I decided to swap directions on my loop from for (var c = 0; c <= 11; c++) to for (var c = 12; c > 0; c++) But as you can see above, I forgot to change it from c++ to c--. Any ideas?? I still have the tab open and I'm hoping to get it back without closing the tab :-) A: With the developer mode, go into resources and find your script and copy and paste it into a text document or a new window. If you can't find it in resources, do a search for a variable or line of code you used. A: One way of breaking the infinite loop is to throw an unhandled exception, which will stop the execution of current call stack. To do so: * *pause the debbuger *find a promising statement inside the loop, for example a function call: foo.bar(args) *in console, overwrite the function to throw : foo.bar=function(){throw 42;} *unpause the debugger worked for me. I haven't tried, but I believe that by overloading getter or setter you can use the trick described above also for assignments and reads, not only for function calls. Also, by setting a variable to undefined, you may cause fatal error (and thus break the loop) if the field of this variable is used in the loop. For example delete foo.tab will break foo.tab[42] or foo.tab.bar. For some reason, simply writting foo=undefined in the console, will not do (perhaps it defines a variable local to the console window named foo). A: How to do it without Developer Mode: * *Open a new tab *Open the Task Manager with Shift-Escape *Kill task *Use back button for the killed tab (JSFiddle won't run the script) *Fix bug *Update Or on MacOS, * *Open Activity Monitor *Kill the first "Google Chrome Helper (Renderer)" process. It's probably JSFiddle *Fix the issue *Run the code A: Run Process Explorer and kill the chrome process that's using lots of CPU...it will "crash" the page and let you reload... A: I couldn't start Chrome's Task Manager while the looping tab was active. I had to select another tab. Then I pressed Shift-Escape to launch the Task Manager, kill the JSFiddle process, re-select the tab, and hit the back button to display the page without running the script. JSFiddle loads the "result" panel using an iframe. As of June 2016, the URL for the frame is the Fiddle URL plus "/show/". I inspected the source code of the iframe and discovered that it loads yet another URL with "/light/". One of these URLs should contain your source code. If your browser supports the view-source URI scheme, you may access your fiddle's source code as follows: * *view-source:jsfiddle.net/user_name/fiddle_hash/revision/light/ *view-source:jsfiddle.net/user_name/fiddle_hash/revision/show/ A: Same problem came up here, I opened up the javascript console in a script paused state. (Paused it using the Developer Tools) Then I changed the variable value so that the while loop would end. A: In case others are stuck after reading the other answers, here's what worked for me (Chrome, Mac). For me the JSFiddle tab was 'stuck' but the rest of Chrome responsive. I had the JavaScript Console open on the Resources pane, but it was unresponsive too. Reloading the page in this state didn't help because JSFiddle would give me the script before I got anything at all. In the end this worked for me; maybe it will help you too... * *While the page is unresponsive, go to Chrome > Preferences > Privacy and disable JavaScript. *Wait for page to die (about 4 or 5 minutes for me); the sad face icon comes up in that tab. *Hit the back button. It should look like JSFiddle is loading, but it won't because funnily enough JSFiddle needs JavaScript just to render a page. *View > Developer > View source *My script, only slightly mangled, was sitting there all innocent like in a div called 'panel_js'. *Highlight, copy, breathe again, learn lesson. A: I had file stuck in a loop and would freeze up the dashboard on JSFiddle as well. * *The only way I could clear was to disable JavaScript in the preferences tab while I had a New Fiddle page open in a different Chrome tab. *Then navigate to All Fiddles. *Delete the Fiddle and then it would give a 404 error. *Turn on the JavaScript and reload the Dashboard. *Was able to continue on making and editing fiddles after that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7616143", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "56" }
Q: objective-c: double pointers to property not allowed? I want to create a method like this: - (void) checkAndUpdateStringProperty: (NSString **) property{ if (...) *property = @"whatever"; } I want to use this to pass in a property for the same class: - (void) somewhereElse{ .... [self checkAndUpdateStringProperty: &self.productName]; } But this gives a syntax error, saying "Address of property expression requested". Any reason why? If I replace the class property with a local variable, it works fine: - (void) somewhereElse{ NSString *name = nil; [self checkAndUpdateStringProperty: &name]; } A: There are very few places in the Apple APIs that a value is passed in this fashion, the main one being NSError. It is really best to just return the result. If you do have a reference parameter the general Apple rule is that it should be the last parameter that that the method name begin with "get" as in getCheckAndUpdateStringProperty. But you can do it, it is just not what we are used to. The error you are seeing is that self.productName is really shorthand for the method call: [self productName] so &self.productName is interpreted as &[self productName]. Further in this case if productName is a @property with a retain attribute the reference counting will be subverted. A: If you are really careful about the ownership attributes, you can get around this issue by staring at the following: [self property] vs: self.property vs: self->property Once you are clear about the difference you can try this: [self checkAndUpdateStringProperty: &self->productName] Note the use of: -> I use this all the time when the property attribute is assign and when it is a primitive, non object type: (float, int, ...) A: Properties should only ever be accessed through their getter and setter methods, with the exception of initializing and deinitializing them in the object's init and dealloc methods (when the object is not in a fully consistent state) -- accessing them any other way defeats their purpose and does not respect their attributes (retain, copy, etc.). The reason why it doesn't compile is because property accessors are syntactic sugar for method calls, and you can't take the address of the return value of a method. self.productName is identical to [self productName], and &[self productName] makes no sense. If you really want to do this, don't do it with a property, do it with just a regular variable (such as a local variable or ivar), and document the semantics of your function: does the calling function need to release the returned object? Etc. For example, the various Apple methods which take an NSError** specify that the error object which is returned, if any, is an autoreleased object, so you should not release it yourself unless you also retain it. A: create a property of that variable,which you want to access in another class (@property(strong,nonatomic) ;) and then synthesise it.... (@synthesize ;) and then access via object name of that class,where you define property and synthesise it..... A: I'd do this using the selectors instead (you'll have to convert it to a c function to get it to work without warning (see here): - (void) checkAndUpdateStringProperty: (SEL)setter { if (...) IMP imp = [self methodForSelector:setter]; void (*func)(id, SEL, id) = (void *)imp; func(self, setter, @"whatever"); } Use this to pass in the selector for the same class: - (void) somewhereElse{ .... [self checkAndUpdateStringProperty:@selector(setProductName:)]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7616147", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: How to find foreign key dependencies of a specific row? If I have a table, TableA: Id 1 2 3 ... And two other tables: TableB: Id, TableAId 1 1 2 1 TableC: Id, TableAId 1, 1 2, 2 Where TableAId is a FK relationship with TableA.Id. How do I determine that TableA, Id 1, has three rows pointing to it? And that TableA, Id 2 has one row pointing to it? And more specifically, how do I identify what those rows are? (their table name and Id) A: I don't have SQL on this computer so I can't give You exact code but here is the way you should go. Please, note that I will use SQL Server terminology. I see no way to do this without dynamic sql, at least in SQL Server. * *Create temporary table #t with columns FK_TBL_NM, FK_CLMN_VAL. *It should not be difficult to get all the fk relationships for pk of TableA: SELECT * FROM sys.foreign_keys WHERE referenced_object_id = OBJECT_ID('TableA') *Use a cursor to iterate thru the result of this query and for each generate and execute dynamic sql that will join TableA and table retrieved from cursor and returns FK_TBL_NM (TableB, TableC, ...) and value of fk column. *Insert the result into #t (it is tricky to get dynamic sql result into table but do a research on stackoverflow) Now you have the table that contains one row for each row in TableB, TableC, ... I know this is feasible because I wrote the code with similar logic for my current project at work just few days ago. Note that you should probably make your code work with pk/fk with more that one column. Also there are different data types for columns. It complicates things a bit but it is possible. Every step I listed above is not difficult to implement. However, if you have any difficulties, search on stackoverflow :) A: In order to find out what FK relationships exist, you need to inspect the sys catalog views in SQL Server - something like: SELECT * FROM sys.foreign_keys WHERE referenced_object_id = OBJECT_ID('TableA') This will list out all foreign key relationships that exist to TableA. Once you have that information, it's a pretty simple JOIN between TableA and any of those other tables involved. Update: once you know that e.g. TableB and TableC reference your TableA, you can find the depdendent rows with a simple JOIN: SELECT c.* FROM dbo.TableC c INNER JOIN dbo.TableA a ON a.ID = c.TableAID -- or whatever column joins the tables..... WHERE....... -- possibly with a WHERE clause... A: You can use the INFORMATION_SCHEMA views to generate select statements to display the rows in question. I have only tested this against the tables provided in the question, but it could be expanded to work in cases where the keys are multiple columns. declare @table_schema nvarchar(50) = 'dbo', @table_name nvarchar(50) = 'TableA', @id int = 1 select fk_col.TABLE_SCHEMA, fk_col.TABLE_NAME, fk_col.COLUMN_NAME, 'select * from ' + fk_col.TABLE_SCHEMA + '.' + fk_col.TABLE_NAME + ' t1 ' + ' inner join ' + @table_schema + '.' + @table_name + ' t2 ' + ' on t1.' + fk_col.COLUMN_NAME + ' = t2.' + pk_col.COLUMN_NAME + ' where t2.' + pk_col.COLUMN_NAME + ' = ' + cast(@id as nvarchar) from INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk join INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE pk_col on pk.CONSTRAINT_SCHEMA = pk_col.CONSTRAINT_SCHEMA and pk.CONSTRAINT_NAME = pk_col.CONSTRAINT_NAME join INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS fk on pk.CONSTRAINT_SCHEMA = fk.UNIQUE_CONSTRAINT_SCHEMA and pk.CONSTRAINT_NAME = fk.UNIQUE_CONSTRAINT_NAME join INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE fk_col on fk_col.CONSTRAINT_SCHEMA = fk.CONSTRAINT_SCHEMA and fk_col.CONSTRAINT_NAME = fk.CONSTRAINT_NAME where pk.TABLE_SCHEMA = @table_schema and pk.TABLE_NAME = @table_name and pk.CONSTRAINT_TYPE = 'PRIMARY KEY' The select statements generated: select * from dbo.TableB t1 inner join dbo.TableA t2 on t1.TableAId = t2.Id where t2.Id = 1 select * from dbo.TableC t1 inner join dbo.TableA t2 on t1.TableAId = t2.Id where t2.Id = 1 and the query results: Id TableAId Id ----------- ----------- ----------- 1 1 1 2 1 1 Id TableAId Id ----------- ----------- ----------- 1 1 1 A: I couldn't find perfect reusable answer for this so combining a few different answers I created a stored procedure to do the job. CREATE PROCEDURE GETLINKEDKEYS @PKTABLE_NAME varchar(32) ,@PKTABLE_ID int AS BEGIN DECLARE @fkeys TABLE ( [PKTABLE_QUALIFIER] varchar(32) ,[PKTABLE_OWNER] varchar(3) ,[PKTABLE_NAME] varchar(32) ,[PKCOLUMN_NAME] varchar(32) ,[FKTABLE_QUALIFIER] varchar(32) ,[FKTABLE_OWNER] varchar(3) ,[FKTABLE_NAME] varchar(32) ,[FKCOLUMN_NAME] varchar(32) ,[FKCOLUMN_PKNAME] varchar(32) ,[KEY_SEQ] int ,[UPDATE_RULE] int ,[DELETE_RULE] int ,[FK_NAME] varchar(64) ,[PK_NAME] varchar(32) ,[DEFERRABILITY] int ); INSERT INTO @fkeys ([PKTABLE_QUALIFIER],[PKTABLE_OWNER],[PKTABLE_NAME],[PKCOLUMN_NAME],[FKTABLE_QUALIFIER],[FKTABLE_OWNER],[FKTABLE_NAME],[FKCOLUMN_NAME],[KEY_SEQ],[UPDATE_RULE],[DELETE_RULE],[FK_NAME],[PK_NAME],[DEFERRABILITY]) EXEC sp_fkeys @PKTABLE_NAME; UPDATE FK SET [FKCOLUMN_PKNAME] = (SELECT [COLUMN_NAME] FROM [INFORMATION_SCHEMA].[KEY_COLUMN_USAGE] WHERE OBJECTPROPERTY(OBJECT_ID([CONSTRAINT_SCHEMA] + '.' + QUOTENAME([CONSTRAINT_NAME])), 'IsPrimaryKey') = 1 AND [TABLE_NAME] = FK.[FKTABLE_NAME]) FROM @fkeys FK DECLARE @StringTable TABLE ([ID] int IDENTITY(1, 1), [Query] varchar(max)); INSERT INTO @StringTable SELECT 'SELECT ''' + [PKTABLE_NAME] + ''' AS ''PrimaryTable'' ' + ',''' + [PKCOLUMN_NAME] + ''' AS ''PrimaryTableColumn'' ' + ',PT.[' + [PKCOLUMN_NAME] + '] AS ''PrimaryTableColumnID'' ' + ',''' + [FKTABLE_NAME] + ''' AS ''ForeignTable'' ' + ',''' + [FKCOLUMN_NAME] + ''' AS ''ForeignTableColumn'' ' + ',FT.[' + [PKCOLUMN_NAME] + '] AS ''ForeignTableColumnID'' ' + (CASE WHEN [FKCOLUMN_PKNAME] IS NULL THEN ',NULL' ELSE ',''' + [FKCOLUMN_PKNAME] + '''' END) + ' AS ''ForeignTablePrimaryColumn''' + (CASE WHEN [FKCOLUMN_PKNAME] IS NULL THEN ',NULL' ELSE ',FT.[' + [FKCOLUMN_PKNAME] + ']' END) + ' AS ''ForeignTablePrimaryColumnID''' + 'FROM [' + [PKTABLE_NAME] + '] PT ' + 'JOIN [' + [FKTABLE_NAME] + '] FT ' + 'ON FT.[' + [FKCOLUMN_NAME] + '] = PT.[' + [PKCOLUMN_NAME] + '] ' + 'WHERE PT.[' + [PKCOLUMN_NAME] + '] = ' + CONVERT(varchar(16), @PKTABLE_ID) FROM @fkeys; DECLARE @matchTable TABLE ( [PrimaryTable] varchar(32) ,[PrimaryTableColumn] varchar(32) ,[PrimaryTableColumnID] int ,[ForeignTable] varchar(32) ,[ForeignTableColumn] varchar(32) ,[ForeignTableColumnID] int ,[ForeignTablePrimaryColumn] varchar(32) ,[ForeignTablePrimaryColumnID] int ); DECLARE @Count int = (SELECT COUNT([ID]) FROM @StringTable); DECLARE @QueryString varchar(max); WHILE @Count > 0 BEGIN SELECT @QueryString = [Query] FROM @StringTable WHERE [ID] = @Count; INSERT INTO @matchTable EXECUTE(@QueryString); SET @Count = @Count - 1; END SELECT * FROM @matchTable; END GO Example : EXECUTE [dbo].[GETLINKEDKEYS] 'Users', 32 PrimaryTable PrimaryTableColumn PrimaryTableColumnID ForeignTable ForeignTableColumn ForeignTableColumnID ForeignTablePrimaryColumn ForeignTablePrimaryColumnID Users UserID 32 UsersInfo UserID 32 UsersInfoID 123 Users UserID 32 Images UserID 32 IamgeID 56 Users UserID 32 UsersLogs UserID 32 NULL NULL
{ "language": "en", "url": "https://stackoverflow.com/questions/7616149", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }