text
stringlengths
8
267k
meta
dict
Q: CodeIgniter Database Search I have a search form which is used by staff to search for a user account. I want the search form to take the input from the user and search the DB for a user that matches it. Here's my DB structure... Users Table -> (id, fname, lname, ip_address....etc.) Here is what I'm using in my model to search for the user... $this->db->or_like('fname', $query); $this->db->or_like('lname', $query); $this->db->or_like('email', $query); $this->db->or_where('ip_address', $query); $query = $this->db->get('users'); This works great for most searches. For example.... Search: Bill returns all users with a first name or last name of bill..... However, a search for a first and last name doesn't return a user even if there is a user that matches. Example.... Search: Bill Gates That search doesn't return the user with the fname of Bill and the lname of Gates. What can I do to make this work? A: You'll have to massage the search term into multiple individual terms. CI will write the query as: WHERE fname LIKE '%Bill Gates%' OR lname LIKE '%Bill Gates%' etc... which will never match, since 'bill gates' never appears in a single field in the database. But if you split it into multiple words, (Bill and Gates) and add each word to the or set individually, you will get matches. The other option, if you're using MyISAM tables, is to use a fulltext index across the 3 fields, which would find 'bill gates', even if bill is one field and gates is in the other. Apparently fulltext support for InnoDB is now actually finally in the development pipeline, but for now it's still myisam only in production code. A: Since you split the first and last name in the database and use the same variable for both or_like() calls, you can only search for one word. You have to split the string at " " (a space) and call or_like() for each part or use a form with 3 separate input fields (imho the better idea).
{ "language": "en", "url": "https://stackoverflow.com/questions/7506240", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javascript Iframe Security Error Within Try/Catch Block In Webkit Browsers When I run the following code in webkit browsers, I get an error outputted to the console despite having my code wrapped in a try/catch block. var externallyFramed = false; try { externallyFramed = top.location.host != location.host; } catch (e) { externallyFramed = true; } The error I get is the following: Unsafe JavaScript attempt to access frame with URL... Is there anything I can do differently to prevent the error from showing up?
{ "language": "en", "url": "https://stackoverflow.com/questions/7506243", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: WCF Configuration for Windows authentication and jQuery I have an ASP.NET MVC application that uses Windows authentication. I'd like that application to call a WCF service that resides in that same application. However, I can't seem to get the configuration piece down for this application. Both the ASP.NET MVC and WCF service reside in the same project. Here's the configuration I have thus far: <system.serviceModel> <behaviors> <serviceBehaviors> <behavior> <serviceDebug includeExceptionDetailInFaults="true" /> <serviceMetadata httpGetEnabled="true" /> </behavior> </serviceBehaviors> </behaviors> <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> <bindings> <basicHttpBinding> <binding> <security mode="TransportCredentialOnly" > <transport clientCredentialType="Windows" proxyCredentialType="Windows" /> </security> </binding> </basicHttpBinding> </bindings> <services> <service name="DashboardService"> <endpoint address="" binding="basicHttpBinding" contract="MyApplication.Services.ICustomService" /> </service> </services> <client> <endpoint address="" binding="basicHttpBinding" contract="MyApplication.Services.ICustomService" /> </client> </system.serviceModel> I've tried to connect to the WCF service using a Service Reference in a different ASP.NET application, The method works correctly and I can return the proper data. However, with this config, I'm getting a 400, Bad Request when I visit http://domain/myservice.svc/method. However, both http://domain/myservice.svc and http://domain/myservice.svc?wsdl work correctly. It seems like I'm overlooking something in my WCF configuration. Any help that can be provided is appreciated. A: I was able to change my configuration to use the webHttpBinding like so: <system.serviceModel> <behaviors> <serviceBehaviors> <behavior> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="true"/> </behavior> </serviceBehaviors> <endpointBehaviors> <behavior name="RestEndpoint"> <webHttp/> </behavior> </endpointBehaviors> </behaviors> <bindings> <webHttpBinding> <binding name ="WindowsRestBinding"> <security mode ="TransportCredentialOnly"> <transport clientCredentialType ="Windows"/> </security> </binding> </webHttpBinding> </bindings> <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> <services> <service name="MyApplication.Services.CustomService"> <endpoint address="" binding="webHttpBinding" bindingConfiguration="WindowsRestBinding" contract="MyApplication.Services.ICustomService" behaviorConfiguration="RestEndpoint" /> </service> </services> A: Try <security mode="Transport" > Instead of <security mode="TransportCredentialOnly" >
{ "language": "en", "url": "https://stackoverflow.com/questions/7506247", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Alpha Detection in Layer OK on Simulator, not iPhone First, check out this very handy extension to CALayer from elsewhere on SO. It helps you determine if a point in a layer's contents-assigned CGImageRef is or isn't transparent. n.b.: There is no guarantee about a layer's contents being representable or responding as if it was a CGImageRef. (This can have implications for broader use of the extension referenced above, granted.) In my case, however, I know that the layers I'm testing have contents that were assigned a CGImageRef. (Hopefully this can't change out from under me after assignment! Plus I notice that contents is retained.) OK, back to the problem at hand. Here's how I'm using the extension. For starters, I've changed the selector from containsPoint: to containsNonTransparentPoint: (I need to keep the original method around.) Now, I have a UIImageView subclass that uses seven CALayer objects. These are used for opacity-based animations (pulsing/glowing effects and on/off states). Each of those seven layers has a known CGImageRef in its contents that effectively "covers" (air quotes) one part of the entire view with its own swath of color. The rest of each image in its respective layer is transparent. In the subclass, I register for single tap gestures. When one arrives, I walk through my layers to see which one was effectively tapped (that is, which one has a non-transparent point where I tapped, first one found wins) and then I can do whatever needs doing. Here's how I handle the gesture: - (IBAction)handleSingleTap:(UIGestureRecognizer *)sender { CGPoint tapPoint = [sender locationInView:sender.view]; // Flip y so 0,0 is at lower left. (Required by layer method below.) tapPoint.y = sender.view.bounds.size.height - tapPoint.y; // Figure out which layer was effectively tapped. First match wins. for (CALayer *layer in myLayers) { if ([layer containsNonTransparentPoint:tapPoint]) { NSLog(@"%@ tapped at (%.0f, %.0f)", layer.name, tapPoint.x, tapPoint.y); // We got our layer! Do something useful with it. return; } } } The good news? All of this works beautifully on the iPhone Simulator with iOS 4.3.2. (FWIW, I'm on Lion running Xcode 4.1.) However, on my iPhone 4 (with iOS 4.3.3), it doesn't even come close! None of my taps seem to match up with any of the layers I'd expect them to. Even if I try the suggestion to use CGContextSetBlendMode when drawing into the 1x1 pixel context, no dice. I am hoping it's pilot error, but I have yet to figure out what the disparity is. The taps do have a pattern but not a discernible one. Perhaps there's a data boundary issue. Perhaps I have to do something other than flip the y coordinate to the lower-left of the image. Just not sure yet. If anyone can please shed some light on what might be amiss, I would be most appreciative! UPDATE, 22 September 2011: First ah-ha moment acquired! The problem isn't Simulator-vs-iPhone. It's Retina vs. Non-Retina! The same symptoms occur in the Simulator when using the Retina version. Perhaps the solution centers around scaling (CTM?) in some way/shape/form. The Quartz 2D Programming Guide also advises that "iOS applications should use UIGraphicsBeginImageContextWithOptions." I feel like I'm very close to the solution here! A: OK! First, the problem wasn't Simulator-vs-iPhone. Rather, it was Retina vs. Non-Retina. The same symptoms occur in the Simulator when using the Retina version. Right away, one starts to think the solution has to do with scaling. A very helpful post over on the Apple Dev Quartz 2D forum (along similar "be mindful of scaling" lines) steered me toward a solution. Now, I'm the first to admit, this solution is NOT pretty, but it does work for Retina and Non-Retina cases. With that, here's the revised code for the aforementioned CALayer extension: // // Checks image at a point (and at a particular scale factor) for transparency. // Point must be with origin at lower-left. // BOOL ImagePointIsTransparent(CGImageRef image, CGFloat scale, CGPoint point) { unsigned char pixel[1] = {0}; CGContextRef context = CGBitmapContextCreate(pixel, 1, 1, 8, 1, NULL, kCGImageAlphaOnly); CGContextSetBlendMode(context, kCGBlendModeCopy); CGContextDrawImage(context, CGRectMake(-point.x, -point.y, CGImageGetWidth(image)/scale, CGImageGetHeight(image)/scale), image); CGContextRelease(context); CGFloat alpha = pixel[0]/255.0; return (alpha < 0.01); } @implementation CALayer (Extensions) - (BOOL)containsNonTransparentPoint:(CGPoint)point scale:(CGFloat)scale { if (CGRectContainsPoint(self.bounds, point)) { if (!ImagePointIsTransparent((CGImageRef)self.contents, scale, point)) return YES; } return NO; } @end In short, we need to know about the scale. If we divide the image width and height by that scale, ta-dah, the hit test now works on Retina and Non-Retina devices! What I don't like about this is the mess I've had to make of that poor selector, now called containsNonTransparentPoint:Scale:. As mentioned in the question, there is never any guarantee what a layer's contents will contain. In my case I am taking care to only use this on layers with a CGImageRef in there, but this won't fly in a more general/reusable case. All this makes me wonder if CALayer is not the best place for this particular extension after all, at least in this new incarnation. Perhaps CGImage, with some layer smarts thrown in, would be cleaner. Imagine doing a hit test on a CGImage but returning the name of the first layer that had non-transparent content at that point. There's still the problem of not knowing which layers have CGImageRefs in them, so some hinting might be required. (Left as an exercise for yours truly and the reader!) UPDATE: After some discussion with a developer at Apple, messing with layers in this fashion is in fact ill-advised. Contrary to what I previously learned (incorrectly?), multiple UIImageViews encapsulated within a UIView are the way to go here. (I always remember learning that you want to keep your views to a minimum. Perhaps in this case it isn't as big a deal.) Nevertheless, I'll keep this answer here for now, but will not mark it as correct. Once I try out and verify the other technique, I will share that here!
{ "language": "en", "url": "https://stackoverflow.com/questions/7506248", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why deadline doesn't work with GAE urlfetch? If I use the following code: result = urlfetch.fetch(url=url_get_devices, payload='', method=urlfetch.POST, headers=headers, deadline=10 ) then I am getting error: File "D:\Work_GAE\test.py", line 27, in get deadline=10 TypeError: fetch() got an unexpected keyword argument 'deadline' But if I remove deadline argument, then it works well. What is wrong here? A: It sounds like you're using a very old version of the App Engine SDK. You should update to the latest version.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506253", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android Developer - Updating an App Published in the Market Prior to publishing my app on the market I could connect my phone via USB and run/debug the app on the phone (signed with development key). Now that I have published it on the market I find that in order to run it on my phone I have to export a signed apk and copy it to my phone's SD card and then install it. This is a hassle but even worse is that I can no longer run the app in debug mode on my phone. I have not seen anyone else complain about this so I presume I am lacking some understanding of the process. Can anyone help? Thanks aussieW A: This means that you will need to uninstall the current application on the device in order to debug. A: I just do a "run" from Eclipse as usual to debug, and I didn't need to sign anything, only when exporting the file to be published. I don't put the file manually in the phone; I have a run configuration that runs the app right on the phone via USB DEBUGGING. The catch is I can't have USB Storage AND Debugging on at the same time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506256", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android: Does getSpeed return the user's speed? I'm confused. This says that getSpeed only returns a value set with setSpeed. But other sources seem to indicate that getSpeed should actually return a speed. The android docs say that getSpeed "Returns the speed of the device over ground in meters/second." Other sources too seem to say that it works to return the speed of the device, e.g. http://comments.gmane.org/gmane.comp.handhelds.android.devel/125386 Detect a speed in android Which is correct? I can't seem to get getSpeed to return a non-zero value, so if it does work, what are some common sticking points that I might be screwing up? I have the manifest set correctly, I believe. A: Speed calculation uses GPS, so you should use GPS location provider and have GPS satellite fix.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506258", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to check if a order has a shipment in Magento? I need to check if an order has already some shipment set. The only data I can use is the increment id of the order. I'm getting an instance of a model order, but I don't see a way I can get a shipment instance. I'm using this code: $order = Mage::getModel('sales/order') ->loadByIncrementId($order_increment_id); But how can I get a shipment instance? I know that I can call Mage::getModel('sales/order_shipment')->loadByIncrementId($shipment_increment_id) but how do I get the shipment increment id? A: Just to make it complete Mage_Sales_Model_Order has public method:hasShipments()which returns number of shipments and internally uses mentioned getShipmentsCollection(). A: Assume that the person who wrote this might have also needed to do what you need to do. Generally, when Magento objects have a one to many relationship you can find a method to load the many on the one. You've got a class alias sales/order. This corresponds to Mage_Sales_Model_Order (in a stock installation). You can find this class at app/code/core/Mage/Sales/Model/Order.php. If you examine this class, there are 7 methods with the word "ship" in them function canShip function setShippingAddress function getShippingAddress function getShip function getShipmentsCollection function hasShip function prepareShip Of those 7, only the semantics of getShipmentsCollection indicate a method for grabbing an order's shipments. So try foreach($order->getShipmentsCollection() as $shipment) { var_dump(get_class($shipment)); //var_dump($shipment->getData()); } Or take a look at the source for getShipmentsCollection public function getShipmentsCollection() { if (empty($this->_shipments)) { if ($this->getId()) { $this->_shipments = Mage::getResourceModel('sales/order_shipment_collection') ->setOrderFilter($this) ->load(); } else { return false; } } return $this->_shipments; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7506259", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: javascript: how to reverse a range.execCommand method If I use the execCommand method to highlight the selected text: document.execCommand("HiliteColor", false, colour); as it is suggested in this page, and then I want to come back and cancel the highlight format (that is, to return to the situation as it was before I highlighted some text), what could I do? A: The following will remove formatting: document.execCommand("RemoveFormat", false, null);
{ "language": "en", "url": "https://stackoverflow.com/questions/7506260", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Delphi XE2. How to compile .exe? I have my Delphi program coded and ready to rock and roll, but I can't find the option to compile the .exe. I'm sure it's obvious, any help? A: go to the Delphi IDE Menu Project -> Compile Project or just press Ctrl F9
{ "language": "en", "url": "https://stackoverflow.com/questions/7506263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Checking for unique output in Python I came across a fun math problem yesterday and have it solved, but with the code I wrote, I had to do a keyboard interrupt or it would run forever, lol. So I changed it to have an end condition, but now it only prints 1 solution and stops. The problem goes like this: "You have the numbers 123456789, in that order. Between each number, you must insert either nothing, a plus sign, or a multiplication sign, so that the resulting expression equals 2002. Write a program that prints all solutions. (There are two.)" import random def try1(param): global solved opers = ['+', '*', ''] hotpotato = ('%s'.join(param) % (random.choice(opers), random.choice(opers), random.choice(opers), random.choice(opers), random.choice(opers), random.choice(opers), random.choice(opers), random.choice(opers), ) ) if eval(hotpotato) == 2002: solved += 1 print "Solution:", hotpotato, "= 2002 :-)" else: pass solved = 0 while solved == 0: try1('123456789') This code prints the first solution it encounters and stops. Can anyone tell me how to get it to print both solutions before it stops? A: Don't use random, enumerate all possible operator combinations (well, you can cut the search space a bit, if the first couple of numbers the result is larger than 2002, there is no way the result is going to be smaller). itertools is your friend. If you do that, your program will finish in no time. If you know that there are exactly two solutions you can return the solution from try1 and do the loop till you collected two different solutions, but that's not really elegant, is it? A: The solution to your problem is, breaking when solved == 2. But your code's real problem is using random. Using random in an algorithm is generally a bad idea. There is a possibility that your code lasts over a century. There is much simplier and faster way using itertools: import itertools for s in itertools.product(("+", "*", ""), repeat=8): z = itertools.izip_longest("123456789", s, fillvalue="") e = "".join(itertools.chain.from_iterable(z)) if eval(e) == 2002: print(e) There is no need to break when two solutions found, because the code already completes in 0.2 seconds :). A: Store your solutions in a set: solutions = set([]) Each time a solution is found, update the set: solutions.append(solution) Sets are nice because there don't store duplicates: >>> len(set([1, 1, 1, 1, 1, 1, 1])) 1 So just loop until the set's size is greater than one: while len(solved) < 2: try1('123456789') Also, you can shorten this code: hotpotato = ('%s'.join(param) % (random.choice(opers), random.choice(opers), random.choice(opers), random.choice(opers), random.choice(opers), random.choice(opers), random.choice(opers), random.choice(opers), ) ) To this: hotpotato = ('%s'.join(param) % (random.choice(opers) for i in range(8)))) A: To receive both (all) solutions you need completely different approach to solve this problem. Check all permutations of inserted operations. How to calculate permutations are shown here: http://www.bearcave.com/random_hacks/permute.html EDIT: Example: ops = ['+', '*'] def gen(ver, i): if i == len(ver): return for op in ops: ver = ver[:i] + op + ver[i:] if eval(ver) == 2002: yield ver for j in range(i + 2, len(ver)): for sol in gen(ver, j): yield sol ver = ver[:i] + ver[i+1:] for sol in gen("123456789", 1): print "solution:", sol Output: solution: 1*2+34*56+7+89 solution: 1*23+45*6*7+89 A: For the record, I would encourage a different approach to search for the solutions, such as suggested in Andy T's answer or yi_H's answer. That said, this answer addresses the issue presented in the question. The code you present will run until one answer is found and stop, since finding the first answer will make solved not equal 0. Since you know there are 2 solutions, you can change your while loop condition: while solved < 2: try1('123456789') In response to Mark's comment that this can lead to duplicated answers, here is code which will make sure you get different solutions: import random def try1(param): global solved try1.prev_soln = [] opers = ['+', '*', ''] hotpotato = ('%s'.join(param) % (random.choice(opers), random.choice(opers), random.choice(opers), random.choice(opers), random.choice(opers), random.choice(opers), random.choice(opers), random.choice(opers), ) ) if eval(hotpotato) == 2002: if hotpotato not in try1.prev_soln: solved += 1 try1.prev_soln.append(hotpotato) print "Solution:", hotpotato, "= 2002 :-)" else: pass solved = 0 while solved < 2: try1('123456789') Of course, this approach assumes 2 solutions. If you had an unknown number of solutions you would not know when to stop, thus my recommendation for another approach to finding the solutions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506264", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Getting the ICO predominant color How can I get the icon predominant color? I am using delphi 2007 A: Here is some messy code i crafted based on this you should find a optimal solution type TElement = packed record ocurrences: Integer; color: TColor; end; Element = ^TElement; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.btn1Click(Sender: TObject); var fname: string; i, j, k, max: Integer; lista_culori: TList; tmp: TColor; el: Element; este: Boolean; test: TIcon; bmp: TBitmap; begin lista_culori := TList.Create; if PromptForFileName(fname, '', '', '', '', false) then begin test := TIcon.Create; bmp := TBitmap.Create; test.LoadFromFile(fname); bmp.Height := test.Height; bmp.Width := test.Width; bmp.Canvas.Draw(0, 0, test); test.Free; for i := 0 to bmp.Width do for j := 0 to bmp.Height do begin tmp := bmp.Canvas.Pixels[i, j]; este := false; for k := 0 to lista_culori.Count - 1 do begin if Element(lista_culori[k])^.color = tmp then begin el := Element(lista_culori[k]); el^.ocurrences := el^.ocurrences + 1; este := True; el := nil; end; end; if not este then begin GetMem(el, SizeOf(TElement)); el^.ocurrences := 0; el^.color := tmp; lista_culori.Add(el); end; end; end; max := Element(lista_culori[0])^.ocurrences; k := 0; for i := 1 to lista_culori.Count - 1 do begin if max < Element(lista_culori[i])^.ocurrences then begin k := i; max := Element(lista_culori[i])^.ocurrences; end; end; ShowMessage(ColorToString(Element(lista_culori[k])^.color)); end;
{ "language": "en", "url": "https://stackoverflow.com/questions/7506267", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Create callback executing foobar twice My model looks like this: after_create :foobar after_update :foobar def foobar update_attributes(:foo => 'bar') end Whenever I create an object. It calls foobar (after_create callback). But it also automatically triggers the after_update callback. Basically, when I create an object its calling foobar twice. How can I prevent this? A: In after_create you're calling update_attributes() which triggers the after_update callback. Basically you're calling it twice. You need to figure out what the proper flow is for your program, and make it such that foobar only gets called once. Right now, the code you've written is executing as designed. One suggestion would be using before_[action] attributes instead to modify the fields in the incoming object. That way the object only gets saved once. The way you've written it, new objects get saved twice - once when they're created, and once when they're updated via update_attributes. I see that this is example code, but I'm not sure how, in after_update, since you explicitly make ANOTHER update, how this isn't getting wrapped up in an infinite loop. Might be able to give a better answer if you post actual code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506269", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to remove characters from a string in VBscript I'm new to vbscript and Stack Overflow, and could really use some help. Currently I'm trying to format a phone number that is read from an image and stored in a variable. Because the images are "dirty" extra characters find their way in, such as periods or parenthesis. I've already restricted the field as much as possible to help prevent picking up extra characters, but alas! For example I want to turn ",123.4567890" into "123 456 7890" (not including the double quotes). Trouble is I won't know what extra characters could potentially be picked up, ruling out a simple replace. My logic is remove any non numeric characters, start from the left, insert a space after the third number, insert a space after the sixth number. Any help would be great, and please feel free to ask for more information if needed. A: Welcome to Stack Overflow. You can remove non-digits using Regex, and concatenate the parts using Mid function. For example: Dim sTest sTest = ",123.4567890" With (New RegExp) .Global = True .Pattern = "\D" 'matches all non-digits sTest = .Replace(sTest, "") 'all non-digits removed End With WScript.Echo Mid(sTest, 1, 3) & " "& Mid(sTest, 4, 3) & " "& Mid(sTest, 7, 4) Or fully using Regex (via a second grouping pattern): Dim sTest sTest = ",123.4567890" With (New RegExp) .Global = True .Pattern = "\D" 'matches all non-digits sTest = .Replace(sTest, "") 'all non-digits removed .Pattern = "(.{3})(.{3})(.{4})" 'grouping sTest = .Replace(sTest, "$1 $2 $3") 'formatted End With WScript.Echo sTest A: Use a first RegExp to clean non-digits from the input and second one using groups for the layout: Function cleanPhoneNumber( sSrc ) Dim reDigit : Set reDigit = New RegExp reDigit.Global = True reDigit.Pattern = "\D" Dim reStruct : Set reStruct = New RegExp reStruct.Pattern = "(.{3})(.{3})(.+)" cleanPhoneNumber = reStruct.Replace( reDigit.Replace( sSrc, "" ), "$1 $2 $3" ) End Function ' cleanPhoneNumber
{ "language": "en", "url": "https://stackoverflow.com/questions/7506270", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: VB.Net ComboBox - Enums and Limiting Values Based on Selection in Another ComboBox The project I'm working on makes extensive use of Enum's to hold unit symbols. Like this... Public Enum AreaSym unknown = 0 in2 mm2 End Enum My Problems began when I realized that my Enum names didn't make good names for the drop downs on my ComboBoxes. I found and implemented a TypeConverter from this C# CodeProject http://www.codeproject.com/KB/cs/LocalizingEnums.aspx?msg=3746572 ... It allows you to assign the Enum Values friendly names in a .Resx file, and it overloads the GetValues function so that it returns the Enums friendly names from the .Resx file. This works well as I can then assign the combobox data source directly to the enum. ComboBox1.DataSource = System.Enum.GetValues(GetType(AreaSym)) However, I realized that when using a Datasource in this manner, I have to manipulate the data source to create a change in the ComboBox. Such as, if I don't want to display unknown to the user, I'd need another way to load my ComboBoxes. This is when I decided to make a List(Of KeyValuePair(AreaSym, String)) Public Function AreaSymbols() As List(Of KeyValuePair(Of AreaSym, String)) AreaSymbols = New List(Of KeyValuePair(Of AreaSym, String)) AreaSymbols.Add(New KeyValuePair(Of AreaSym, String)(AreaSym.in2, "in²")) AreaSymbols.Add(New KeyValuePair(Of AreaSym, String)(AreaSym.mm2, "mm²")) Return AreaSymbols End Function This is great because now I can control exactly what goes into the combo box using the list. ComboBox1.DataSource = UnitNameList.AreaSymbols ComboBox1.DisplayMember = "Value" ComboBox1.ValueMember = "Key" However, I've found that using a DataSource has stopped me from doing two things. * *When the form loads, I want the ComboBox itself to show as either empty with no text, or to show the Text I've input in the Text Property. Currently using the DataSource, it always is populated with the first item in the list. *I'd like to be able to easily limit the items in the list, based on the selection of items in another list. Classic example would be two ComboBoxes filled with the exact same values (1,2,3) & (1,2,3). When you choose 1 in ComboBox one, only (2,3) are available for selection in ComboBox 2. I realize that I could probably easily do that if I was using Items, instead of a data source, I'm just not sure what the best way to do that would be because of my need to have the key, value pair of enums and strings...
{ "language": "en", "url": "https://stackoverflow.com/questions/7506271", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to replace a substring within double parentheses in Java? I need to replace a substring within double parentheses with an empty one. I use: source = source.replaceAll("\(.+?\)", ""); The substrings within single parentheses are removed. Instead, when I try with a substring within double parentheses the entire substring is removed but the last ')' remains. What's wrong here? Thanks in advance. A: source.replaceAll("\(\([^\(]*\)\)", ""); ? (not tested) A: The +? means that your match is going to take the least amount of characters possible, meaning that it will grab the inner parenthesized statement. Try: source = source.replaceAll("\(?\(.+?\)\)?", ""); I've just wrapped your regex with \(? and \)?.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506273", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: mvc3 form for a IEnumerable I have a model that I would like have a mass update page for, but am having trouble. My ViewModel: public class ApproveView { public IEnumerable<MyObject> ObjectList { get; set; } } In my view I have: foreach (var item in Model.ObjectList) { <div> <table class="form" width="100%"> <tr> <td>@Html.LabelFor(model => item.Accurate)<br /> @Html.RadioButtonFor(model => item.Accurate, true) Yes @Html.RadioButtonFor(model => item.Accurate, false) No @Html.ValidationMessageFor(model => item.Accurate) </td> <td> @Html.LabelFor(model => item.Comments)<br /> @Html.TextAreaFor(model => item.Comments)<br /> @Html.ValidationMessageFor(model => item.Comments) </td> </tr> </table> @Html.HiddenFor(model => item.ID) @Html.HiddenFor(model => item.CreatedOn) @Html.HiddenFor(model => item.CreatedBy) @Html.HiddenFor(model => item.ModifiedOn) @Html.HiddenFor(model => item.ModifiedBy) <hr /> } This loops over my objects and prints the form. The trouble is that all of the fields of the same type have the same name. So, for example, all of my radio buttons are connected and I can only select one. how do I make the names for each field unique and associated with that object? Am I even on the right track or is there a better way to do this? A: Check this post: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx You need to create editor for your entity. Hope it helps. A: You could also do it a bit more manually: @{var count = 0;} @foreach (var item in Model.ObjectList){ <div> <table class="form"> <tr> <td>@Html.Label("Accurate" + count, item.Accurate)<br /> @Html.RadioButton("AccurateTrue" + count, true) Yes @Html.RadioButton("AccurateFalse" + count, false) No @Html.ValidationMessage("ValidationAccurate" + count, item.Accurate) </td> <td> @Html.Label("CommentsLabel" + count, item.Comments)<br /> @Html.TextArea("Comments" + count, item.Comments)<br /> @Html.ValidationMessage("ValidationComment" + count, item.Comments) </td> </tr> </table> @Html.Hidden("ID" + count, item.ID) @Html.Hidden("CreatedOn" + count, item.CreatedOn) @Html.Hidden("CreatedBy" + count, item.CreatedBy) @Html.Hidden("ModifiedOn" + count, item.ModifiedOn) @Html.Hidden("ModifiedBy" + count, item.ModifiedBy) <hr /> @count++; @}
{ "language": "en", "url": "https://stackoverflow.com/questions/7506277", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How do I add a device to Xcode devices? I have an iPad and an iPhone. My iPhone is listed under devices in Xcode, and I'm trying to add my iPad. Q: How do I add a device in Xcode? A: Connect your device to your Mac with cable. * *Open XCode *Window -> Devices & Simulators *Tap on your device *Tap to check on "Show as run destination" *Tap to check on "Connect via network" A: Open Xcode. Plug in the device. Follow the prompts. A: Sometimes plugging in the device does not bring up the window. In this case, from the Xcode menu, select Window and then Organizer. A: * *Open Xcode *Window -> Devices & Simulators *On the bottom left of the Devices window is a "+" Sign, Click on it. *Choose a connected device from the list to setup *click "Next" *when complete Click "Done" *Disconnect and Reconnect the Device A: Plug your device directly into your mac, don't go through a USB hub as in my case. As soon as I went directly from iPhone to mac, it showed up. A: open xcode and in the above option => "Window" click and select " Devices and simulators ". In the opened window you can see bottom left side "+" button . click and add your device A: I added my iPhone,which had the same issue, by changing my deployment target to match the OS on my phone, selecting my phone in the simulation bar (by the play stop links) and clicking the fix issue link. A: Connect the device -> Open Xcode -> Click the top runner bar, select the connected device (you may need to scroll up).
{ "language": "en", "url": "https://stackoverflow.com/questions/7506281", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: GAE's urlfetch doesn't work with port 10312? I am getting the following warning: WARNING 2011-09-21 20:25:32,259 urlfetch_stub.py] urlfetch received https://z_c l.zzzz.me:10312/zzzz/Data/0 ; port 10312 is not allowed in production! Is there anyway to use that port in Production? A: Update your SDK version! Since march 2010 (SDK 1.3.2), GAE has allowed a wider range of ports: 80-90, 440-450, 1024-65535. They switched from: PORTS_ALLOWED_IN_PRODUCTION = ( None, '80', '443', '4443', '8080', '8081', '8082', '8083', '8084', '8085', '8086', '8087', '8088', '8089', '8188', '8444', '8990') if port not in PORTS_ALLOWED_IN_PRODUCTION: logging.warning( 'urlfetch received %s ; port %s is not allowed in production!' % (url, port)) to: def _IsAllowedPort(port): if port is None: return True try: port = int(port) except ValueError, e: return False if ((port >= 80 and port <= 90) or (port >= 440 and port <= 450) or port >= 1024): return True return False if not _IsAllowedPort(port): logging.warning( 'urlfetch received %s ; port %s is not allowed in production!' % (url, port))
{ "language": "en", "url": "https://stackoverflow.com/questions/7506283", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Determining shutdown time of ExecutorService I have an ExecutorService that processes some tasks. The client threads can call shutdown() on the ExecutorService. I want to run some cleanup code after the ExecutorService has completely shutdown. Is there a mechanism to run a callback method after the ExecutorService has completed its shutdown. NOTE: * *I cannot call shutdownNow() *The clean-up code must run after the shutdown() is completed. *The ExecutorService is a newCachedThreadPoolExecutor(); A: Start another thread/executor-managed-runnable that checks ExecutorService.awaitTermination(...) in a try-catch statement in a loop until it returns true, then run your shutdown handling code. The loop is necessary because the method might return prematurely when interrupted. Something like this: public class ShutdownHandler implements Runnable { private final ExecutorService service; public ShutdownHandler(final ExecutorService service) { this.service = service; } @Override public void run() { boolean terminated = false; while (!terminated) { try { terminated = service.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS); } catch (final InterruptedException ex) { // check again until terminated } } // your shutdown handling code here } } A: I would extends and override: public class MyExecutorService extends ThreadPoolExecutor { @Override public void shutdown() { super.shutdown(); // do what you need to do here } } Something like that A: Well, if you call executorService.invokeAll(myListOfCallableTasks) and them executorService.shutDown() the thread calling that will block until all the tasks are finished: http://download.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html#invokeAll(java.util.Collection)
{ "language": "en", "url": "https://stackoverflow.com/questions/7506292", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to add eventHandlers to Widget added dynamicaly to a view using MVP I have a view which reprents the BreadCrumb of a website, I update the view by setting the crumbs like this public void setCrumb(ArrayList<Crumb> crumbs) { content.clear(); for (int i=0;i<crumbs.size()-1; i++){ Anchor anchor = new Anchor(crumbs.get(i).getText()) content.add(anchor); content.add(new InlineHTML(" > ")); } content.add(crumbs.get(crumbs.size()-1).getText()); } Now, I want to add EventHandlers to every Anchor added. I could just set the handler in the for loop by doing something like anchor.addClickHandler(...) but I'am using MVP, so the view doesn't have to manage handlers... I guess. In the presenter I have access to the panel that has all the anchors. My question is : How to access the anchors from the presenter and set the eventHandler ? A: In an MVP environment, creating of UI elements and catching events should happen in the View and the View should then handle those events and call to the Presenter to take appropriate action, like so: public void setCrumb(ArrayList<Crumb> crumbs) { content.clear(); for (int i=0;i<crumbs.size()-1; i++){ Anchor anchor = new Anchor(crumbs.get(i).getText()); anchor.addClickHandler(new ClickHandler(){ @Override public void onClick(ClickEvent event) { presenter.doSomethingAboutAnchorClicks(...); } }); content.add(anchor); content.add(new InlineHTML(" > ")); } content.add(crumbs.get(crumbs.size()-1).getText()); } And in the Presenter, you want to have a method handleEvent(Event event) that can consume the events, and a method that calls to the View to setCrumb(crumbs). It sounds to me like you're looking at MVP as the same as MVC. The difference is that handling events is the job of the Controller in MVC, while that job belongs to the View in MVP. There are some great resources out there on MVP, and you should definitely check them out. For basics, you can see the Wikipedia Article: Model-View-Presenter, which also contains references to several other great resources. EDIT: here's some code from my personal use case, which is quite similar. This all happens in the View, based on a regionReportElement provided by the Presenter. private Map<String, Anchor> breadCrumbs = new TreeMap<String, Anchor>(); private Map<String, ReportElement> reportElements = new TreeMap<String, ReportElement>(); // .... other stuff ... @Override public void addReportElement(final ReportElement reportElement) { Anchor anchor = new Anchor(reportElement.getShortName()); anchor.addClickHandler(new ClickHandler(){ @Override public void onClick(ClickEvent event) { presenter.onReportElementSelect(reportElement.getId()); } }); reportElements.put(reportElement.getId(), reportElement); if (breadCrumbs.get(reportElement.getId()) == null) { breadCrumbs.put(reportElement.getId(), anchor); if (breadCrumbs.size() > 0) { breadCrumbContainer.add(new Label(" > ")); } breadCrumbContainer.add(anchor); } } // .... other stuff ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7506295", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do you load balance Peoplesoft report repositories? When setting up a load balanced Peopletools/Peoplesoft environment( 2 web, 2 app, 2 process schedulers, all on separate hardware), how do you configure the report repository/repositories? The intent is to have two totally indepenent stacks but also allow reports run on one side to be available from the other. A: I have a single report repository that is on a shared area accessible to both sides/sets of the stack. I've never tried having 2 report repositories, but it sounds like a replication nightmare. If it can be done I'd be interested to hear more. A: This is not necessary, but required in case you have load on report nodes. This can be achieved by creating two report nodes with differrent domain names and needs to be configured through web server config file. Please don't forget to make one report node master and second one slave. Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/7506312", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How does Cake PHP know when a Controllers name is Plural or not I had a couple of cakePHP issues mostly because the names of my Controllers contained either non-plural or non nouns. Now my question is how does cakePHP know what the plural wording is for the controllers and if it's plural and if it's a noun, because I had issues when I named the controller hear_aboutus.php HearAboutUs class, and cake automatically knew the plural for medium and that is media, how does cakePHP find these? A: The inflector class handles that. Here's the source: https://github.com/cakephp/cakephp/blob/master/cake/libs/inflector.php
{ "language": "en", "url": "https://stackoverflow.com/questions/7506315", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery change variable on click? i am sure its a simple thing. But i cant find the solution. My Code: var lang='de'; $('#en').click(function (){ lang='en'; }); The variable dont change / updates on click, why? Thanks! Solution: works not local only on Webserver for me. A: I tried this and it seems to work fine for me. More than likely you have a scope issue. jsFiddle A: Sure it does. Here is the jsFiddle test - http://jsfiddle.net/RfDCU/ With your Html revision it works too - http://jsfiddle.net/RfDCU/1/ Are you sure the lang variable is within function scope? A: Maybe you are missing the document.ready ? $(function(){ var lang='de'; $('#en').click(function (){ lang='en'; }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7506317", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Plot different conditions & subjects at once in Mathematica Please Consider : Needs["ErrorBarPlots`"]; fixNumberF1F6 = {{{7.11`, 7.51`, 11.14`, 8.19`, 6.58`}, {2.14`, 2.33`,2.25`, 1.53`,1.71`}}, {{4.69`, 4.79`, 3.78,4.34`, 4.8`}, {2.22`, 2.71`, 3.18`, 2.29`, 1.93`}}} fixNumberF1F6[[1,1]] refers to the mean fixation number for each subject for condition 1, fixNumberF1F6[[1,2]] the standard Deviation of those means. fixNumberF1F6[[2]] refers to condition 2. plotOptionsXX[title_, yName_, xName_, colors_: Black] := {Frame -> {{True, False}, {True, False}}, PlotStyle -> colors, PlotLabel -> Style[title, Bold, 14, Opacity[1], FontFamily -> "Helvetica"], PlotStyle -> Directive[Black, PointSize[Medium]], PlotRangePadding -> 0, Frame -> {{True, False}, {True, False}}, LabelStyle -> Directive[Black, Bold, 12], FrameLabel -> {{Style[yName, Opacity[1]], None}, {Style[xName, Opacity[1]], None}}, FrameStyle -> Opacity[0], FrameTicksStyle -> Opacity[1], AxesStyle -> Directive[Black, 12], ImageSize -> laTaille}; ErrorListPlot[fixNumberF1F6[[#]] // Transpose, PlotRange -> {{0, 6}, {0, 15}}, ImageSize -> 300, FrameTicks ->{{Range[1, 13, 2], None},{{1, 2, 3, 4, 5}, None}}, PlotStyle -> Directive[Black, AbsolutePointSize[10], AbsoluteThickness[2]], plotOptionsXX["Mean Fixation number", "Fixation Nuber", "SubNo"]] & /@ Range[2] The Plot On the Left represent each subject average fixation number along with the standard deviation for condition 1. On the right for condition 2. How could I plot them both on 1 plot ? If this : fixNumberF1F6across = {{8.10, 1.99}, {4.48, 2.46}} was the mean and SD across subject, How could I show both ? -How can I show 2 conditions on a similar plot for different subjects -How could I show the group mean and SD on it to. A: Edit: I started from over. Given how the data are simple and clean, it may be easiest to use ListPlot and add the bars via an Epilog. You can still tweak it a bit--e.g. put a slight space between the blue and red data points and bars, add a legend, etc, but the basic idea is there. data = {{{7.11`, 7.51`, 11.14`, 8.19`, 6.58`}, {2.14`, 2.33`, 2.25`, 1.53`, 1.71`}}, {{4.69`, 4.79`, 3.78, 4.34`, 4.8`}, {2.22`, 2.71`, 3.18`, 2.29`, 1.93`}}}; ListPlot[{data[[1, 1]], data[[2, 1]]}, PlotStyle -> {{PointSize[.025], Red}, {PointSize[0.025], Blue}}, Frame -> True, PlotRange -> {{0.5, 5.5}, {0, 14}}, FrameTicks -> {{Automatic, Automatic}, {Range[5], None}}, FrameLabel -> {{"Fixation (ms)", None}, {"Subject", None}}, Epilog -> {{Red, Thickness[0.003], Dashed, Line[{{0, m1 = Mean@data[[1, 1]]}, {5.5, m1}}], Blue, Line[{{0, m1 = Mean@data[[2, 1]]}, {5.5, m1}}]}, Thickness[0.005], Red, Line[{{#[[1]], #[[2, 1]]}, {#[[1]], #[[2, 2]]}}] & /@ Transpose@{Range[5], ({#[[1]] + #[[2]], #[[1]] - #[[2]]} & /@ Transpose@data[[1]])}, Thickness[0.005], Blue, Line[{{#[[1]], #[[2, 1]]}, {#[[1]], #[[2, 2]]}}] & /@ Transpose@{Range[5], ({#[[1]] + #[[2]], #[[1]] - #[[2]]} & /@ Transpose@data[[2]])}, }] The BoxWhiskerChart below is from your data. If this looks vaguely like something you are interested in, it could be modified so that the spread from the 25th percentile to the 75% percentile is altered to reflect the spread of one s.d. above and below the mean. And, yes, it is easy to overlay the group means (N=5) onto the Chart. [The reason there isn't perfect symmetry around the mean is that I used your means and standard deviations to generate raw data, assuming a normal distribution. I only used 100 data points per trial, so a little skewing is natural. This would not happen if we were to tweak the chart to reflect standard deviations, which are symmetrical.] A: For any number of series: plotseries[a_] := Module [{col = ColorData[22, "ColorList"]}, Plot[Evaluate@(Piecewise[{#[[2]], #[[1]] - 1/3 <= x <= #[[1]] + 1/3} & /@ Thread[List[Range@Length@#, #]]] & /@ ({a[[#, 1]] + a[[#, 2]], a[[#, 1]] - a[[#, 2]]}) & /@ (Range@Length@a)), {x, 0, 1 + Length@(a[[1, 1]])}, ClippingStyle -> None, PlotStyle -> {None}, Exclusions -> False, Filling -> ({2 # - 1 -> {{2 #}, Directive[col[[#]], Opacity[.2]]}} & /@ Range@Length@a), Ticks -> {Range@Length[a[[1, 1]]], Range@#2 &}, AxesLabel -> {Style["Subject", Medium, Bold], Style["Fixation Time", Medium, Bold]}, Epilog -> MapIndexed[{Directive[col[[#2[[1]]]], PointSize[.03]], Point@Thread[List[Range@Length[#1[[1]]], #1[[1]]]]} &, a] ] ] b = Table[{Table[j^(i/3) + i, {j, 6}], Table[1, {j, 6}]}, {i, 1, 3}]; plotseries[b] A: I don't work very much with error plots, so this might very well be a non-standard form of displaying the data and hastily put together based on the example in the documentation for ErrorBarFunction. (*split it up so it's easier to follow*) meanCond1 = fixNumberF1F6[[1, 1]]; stdCond1 = fixNumberF1F6[[1, 2]]; meanCond2 = fixNumberF1F6[[2, 1]]; stdCond2 = fixNumberF1F6[[2, 2]]; x1 = Transpose@{meanCond1, meanCond2}; x2 = ErrorBar @@@ Transpose@{stdCond1, stdCond2}; Show@(ErrorListPlot[{#1}, ErrorBarFunction -> Function[{coords, errs}, {Opacity[0.2], EdgeForm[{#2}], Rectangle[coords + {errs[[1, 1]], errs[[2, 1]]}, coords + {errs[[1, 2]], errs[[2, 2]]}]}], PlotStyle -> #2, Axes -> False, Frame -> True, FrameLabel -> {"Condition 1", "Condition 2"}] & @@@ Transpose@{Transpose@{x1, x2}, {Blue, Yellow, Green, Gray, Red}}) Each dot is a different subject. The x coordinate is the mean for condition 1 and the y coordinate is the mean for condition 2. The lengths of the sides of the rectangles are the respective standard deviations. So while it does overlap, if you're prudent in choosing colors (and if there aren't too many subjects), it could perhaps work. A: ErrorListPlot[Transpose /@ fixNumberF1F6, PlotRange -> {{0, 6}, {0, 15}}, ImageSize -> 300, FrameTicks -> {{Range[1, 13, 2], None}, {{1, 2, 3, 4, 5}, None}}, PlotStyle -> { Directive[Opacity[0.6],Black, AbsolutePointSize[10], AbsoluteThickness[2]], Directive[Opacity[0.6],Gray, AbsolutePointSize[10], AbsoluteThickness[2]] }, plotOptionsXX["Mean Fixation number", "Fixation Number", "SubNo"] ] ErrorListPlot[fixNumberF1F6across, PlotRange -> {{0, 3}, {0, 15}}, ImageSize -> 300, FrameTicks -> {{Range[1, 13, 2], None}, {{1, 2}, None}}, PlotStyle -> Directive[Black, AbsolutePointSize[10], AbsoluteThickness[2]], plotOptionsXX["Mean Fixation number", "Fixation Number", "Condition Number"] ] As to the 3rd. I don't see how you can talk about group means if you want to show the data of the individual subjects. The 4th (5th?) question is totally unclear. I suggest you remove those questions as they don't seem to be specific to Mathematica programming.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506320", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to access the {exefile}.appconfig settings file How is it possible to access the {exefile}.appconfig settings file? It is mentioned in many tutorials, but how can I get to it in Visual Studio? A: You're looking for the ConfigurationManager class. A: If you mean the configurations of the section of the App.config then: * *Add the a reference System.Configuration to your project. *Use the ConfigurationManager class like this: var value = ConfigurationManager.AppSettings["key"]; Another option is to use Visual Studio to manage your Settings: * *Double click in the Solution Explorer at "Properties". *Open the tab "Settings". *Click into the center of the tab and then enter you settings.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506325", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Embed Java into a C++ application? I got an application written in C++ and I am able to extend the applications functionality by writing plugins in C++ for it. What I basically want to do is to embed Java into this application. This has already been done with Python (not done by me). I read something about JNI but there is always the speech from a full programm that uses Java classes. What I'd like to do is, to use classes from C++ in Java to interact with the application. It's a 3D app in this case, called Cinema 4D. Is there a way to compile and evaluate Java code while the application is running (in some sort of scripting language) using JNI or anything like it ? Example imaginary code after the embedding was done: import c4d.documents.*; class Main { public static void main() { BaseDocument doc = GetActiveDocument(); BaseObject op = doc.GetActiveObject(); if (op != null) { op.Remove(); } } } This code should interact with Cinema 4D to delete the selected object. A: You can embed a JVM within your application. Oracle's official reference book has some more details. The synopsis of it is: #include <jni.h> /* where everything is defined */ int main() { JavaVM *jvm; /* denotes a Java VM */ JNIEnv *env; /* pointer to native method interface */ JDK1_1InitArgs vm_args; /* JDK 1.1 VM initialization arguments */ vm_args.version = 0x00010001; /* New in 1.1.2: VM version */ /* Get the default initialization arguments and set the class * path */ JNI_GetDefaultJavaVMInitArgs(&vm_args); vm_args.classpath = ...; /* load and initialize a Java VM, return a JNI interface * pointer in env */ JNI_CreateJavaVM(&jvm, &env, &vm_args); /* invoke the Main.test method using the JNI */ jclass cls = env->FindClass("Main"); jmethodID mid = env->GetStaticMethodID(cls, "test", "(I)V"); env->CallStaticVoidMethod(cls, mid, 100); /* We could have created an Object and called methods on it instead */ /* We are done. */ jvm->DestroyJavaVM(); } You can do far more sophisticated things if you want (e.g. custom class loaders) but that's about it in terms of the bare minimum needed to get a JVM working within your application. A: There seems to be some confusion over whether you want to embed Java into the C++ app or the other way around. I will take each case. * *For embedding java into c++ app, you can make a socket call to the java program. On java end, you use SocketServer and on the C++ end, you use the General Socket Layer library. This is by far the easiest and most scalable approach. As your java workload keeps increasing, you keep adding additional jvm. Slightly complicated to deploy but, it works really well. *For embedding C++ app in java. This is simple. You compile C++ app into a shared library and use JNI to invoke it. A: What I basically want to do is to embed Java into this application. This has already been done with Python (not done by me). The JNI Invocation API supports this, as described by @awoodland. Here's a current link, for Java 6/7. What I'd like to do is, to use classes from C++ in Java to interact with the application. It's a 3D app in this case, called Cinema 4D. For this you could use one of the following: * *Java native methods implemented in C *JNA *SWIG Is there a way to compile and evaluate Java code while the application is running (in some sort of scripting language) using JNI or anything like it ? BeanShell or Groovy, among others, might be of interest to you. Both support dynamically interpreted code that runs on the JVM. A: I've been working in something similar lately. What worked for me was using the library jni.h that comes when you install java (Java\jdk[version]\include) and creating a dll with c/c++ code in visual studio. For example: Test.h //declare the method you want to implement in c/c++ in the header //include the jni header #include <jni.h> JNIEXPORT void JNICALL Java_Test_print(JNIEnv *, jobject); //Java_[Class Name]_[Method Name](pointer to JVM, java object); Test.cpp extern "C" JNIEXPORT void JNICALL Java_WinampController_printTrackInfo (JNIEnv *env, jobject obj){ printf("Hey, I'm a java method in c (or not?)\n"); } Then create a dll with Visual Studio and load the dll within a static block. I didn't try that without compiling the c/c++ code in a dll, maybe there's another way to call the c/c++ code. But that's how you implement it. Test.java //declare the same method native inside a class in java public class Test{ static { System.loadLibrary("Test"); //load the dll } public native void print(); } //after that you just call test.print() normally So, you just do that and implement java methods with all c/c++ you want. If you still don't know how to do it, enlighten yourself here: Java Native Interface Specification - Oracle Java Native Interface - Wikipedia A: For the scenario you are describing JNI is probably the best way to go. You would be exposing the functionality of your C++ app as a DLL that can be incorporated into and used from a Java application. A: You probably need to rethink your design. Java is not a good choice for this kind of tasks. There is no eval() function in java standard library similar to eval() from python or shell. You can create a java VM in C++ code using JNI but it's kind of heavy. There is still issue how to create a bytecode from a java source. You will have to embed a lot of code to compile and run java code in C++. Don't do that. There must be better solution. You can for example use some RPC (SOAP, XML-RPC, Corba) between your C++ code and separate java code. If you need to do some eval()-like java invocation, you can use Groovy or Jython (both has eval(), access to all standard java library and can run regular java classes).
{ "language": "en", "url": "https://stackoverflow.com/questions/7506329", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "26" }
Q: How to get details of DownloadError? I do the following: try: result = urlfetch.fetch(url=some_url, ... except DownloadError: self.response.out.write('DownloadError') logging.error('DownloadError') except Error: self.response.out.write('Error') logging.error('Error') Is there any way to get some more detailed description on what happened? A: You should use logging.exception to add the Exception to the ERROR logging message: try: result = urlfetch.fetch(url=some_url, ... except DownloadError, exception: self.response.out.write('Oops, DownloadError: %s' % exception) logging.exception('DownloadError') except Error: self.response.out.write('Oops, Error') logging.exception('Error') A: In short, no. A download error is usually a timeout in our experience - something on the back end taking too long to respond (first byte). If it is receiving data, it looks like GAE will wait and throw a Deadline exception instead after your 10 seconds is up. Does it ever succeed? Your choices on how to deal with d/l exceptions will vary depending on the back-end. If you're taking the simplistic route and just retrying, beware of quotas and limiters - chances are your requests are indeed reaching the other system, and just aren't coming back in time. Very easy to blow past limiters this way. J
{ "language": "en", "url": "https://stackoverflow.com/questions/7506330", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Accordion navigation open and close on mouseover/mouseleave jQuery I'm using the jQuery accordion plugin and I need help with my accordion menu, the menu displays submenu links on mouseover but closes the main links only after hover on another main link. I want the sub links to show when I hover the mouse over but also to hide after moving the mouse out of the main link. I would appreciate your help. See code below: Here is the HTML <head> <title>Accordion Test</title> <link rel="stylesheet" href="accordionDemo.css" /> <script type="text/javascript" src="../lib/jquery.js"></script> <script type="text/javascript" src="../lib/chili-1.7.pack.js"></script> <script type="text/javascript" src="../lib/jquery.easing.js"></script> <script type="text/javascript" src="../lib/jquery.dimensions.js"></script> <script type="text/javascript" src="../jquery.accordion.js"></script> <script type="text/javascript"> jQuery().ready(function(){ // simple accordion with mouseover event jQuery('#navigation').accordion({ active: false, header: '.head', navigation: true, event: 'mouseover', fillSpace: true, animated: 'easeslide' }); }); </script> </head> <body> <div id="wrapper"> <div id="navBar"> <ul id="navigation"> <li> <a class="head" href="?p=1">About SfT</a> <ul> <li><a href="?p=1.1">sub1</a></li> <li><a href="?p=1.2">sub2</a></li> <li><a href="?p=1.3">sub3</a></li> <li><a href="?p=1.4.1">sub4</a></li> <li><a href="?p=1.4.2">sub4.1</a></li> <li><a href="?p=1.4.3">sub4.2</a></li> <li><a href="?p=1.4.4">sub4.3</a></li> <li><a href="?p=1.5">sub5</a></li> </ul> </li> <li> <a class="head" href="?p=1.2">Your Life</a> <ul> <li><a href="?p=1.2.1">sub1</a></li> <li><a href="?p=1.2.2">sub2</a></li> <li><a href="?p=1.2.3">sub3</a></li> <li><a href="?p=1.2.4">sub4</a></li> <li><a href="?p=1.2.5">sub5</a></li> </ul> </li> <li> <a class="head" href="?p=1.3">Your Health</a> <ul> <li><a href="?p=accordionTest2.html">sub1</a></li> <li><a href="?p=1.3.3">sub2</a></li> <li><a href="?p=1.3.4">sub3</a></li> <li><a href="?p=1.3.5">sub4</a></li> <li><a href="?p=1.3.6">sub5</a></li> </ul> </li> <li> <a class="head" href="?p=1.3">Your Call</a> <ul> <li><a href="?p=1.4.1">sub1</a></li> <li><a href="?p=1.4.2">sub2</a></li> <li><a href="?p=1.4.3">sub3</a></li> <li><a href="?p=1.4.4">sub4</a></li> <li><a href="?p=1.4.5">sub5</a></li> </ul> </li> </ul> </div> </div> <!--end wrapper--> </body> </html> This is the CSS: * { margin: 0; padding: 0; } body { margin: 0; padding: 0; font-size: small; color: #333 } #wrapper { width:600px; margin:0 auto; padding-top:100px; } #navBar { height:380px; margin-bottom:1em; } #navigation { margin:0px; padding:0px; text-indent:0px; /*background-color:#EFEFEF; sublists background color */ width:200px; } #navigation a.head { /* list header */ height: 40px; cursor:pointer; background: url(collapsed.gif) no-repeat scroll 3px 4px; /* list header bg color and img settings */ color:#999; display:block; font-weight:bold; font-size: 22px; margin:0px; padding:0px; text-indent:20px; text-decoration: none; } #navigation a.head:hover { color:#900; } #navigation a.selected { background-image: url(expanded.gif); color:#900; } #navigation a.current { color: #F60;; font-weight:bold; } #navigation ul { margin:0px; padding:0px; text-indent:0px; } #navigation li { list-style:none outside none; /*display:inline;*/ padding:5px 0 5px 0; } #navigation li li a { color:#000000; display:block; font-size:16px; text-indent:20px; text-decoration: none; } #navigation li li a:hover { /* sublist hover state bg and color */ color:#F60;; font-weight:bold; } And this is the accordion plugin code: /* * jQuery UI Accordion 1.6 * * Copyright (c) 2007 Jörn Zaefferer * * http://docs.jquery.com/UI/Accordion * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Revision: $Id: jquery.accordion.js 4876 2008-03-08 11:49:04Z joern.zaefferer $ * */ ;(function($) { // If the UI scope is not available, add it $.ui = $.ui || {}; $.fn.extend({ accordion: function(options, data) { var args = Array.prototype.slice.call(arguments, 1); return this.each(function() { if (typeof options == "string") { var accordion = $.data(this, "ui-accordion"); accordion[options].apply(accordion, args); // INIT with optional options } else if (!$(this).is(".ui-accordion")) $.data(this, "ui-accordion", new $.ui.accordion(this, options)); }); }, // deprecated, use accordion("activate", index) instead activate: function(index) { return this.accordion("activate", index); } }); $.ui.accordion = function(container, options) { // setup configuration this.options = options = $.extend({}, $.ui.accordion.defaults, options); this.element = container; $(container).addClass("ui-accordion"); if ( options.navigation ) { var current = $(container).find("a").filter(options.navigationFilter); if ( current.length ) { if ( current.filter(options.header).length ) { options.active = current; } else { options.active = current.parent().parent().prev(); current.addClass("current"); } } } // calculate active if not specified, using the first header options.headers = $(container).find(options.header); options.active = findActive(options.headers, options.active); if ( options.fillSpace ) { var maxHeight = $(container).parent().height(); options.headers.each(function() { maxHeight -= $(this).outerHeight(); }); var maxPadding = 0; options.headers.next().each(function() { maxPadding = Math.max(maxPadding, $(this).innerHeight() - $(this).height()); }).height(maxHeight - maxPadding); } else if ( options.autoheight ) { var maxHeight = 0; options.headers.next().each(function() { maxHeight = Math.max(maxHeight, $(this).outerHeight()); }).height(maxHeight); } options.headers .not(options.active || "") .next() .hide(); options.active.parent().andSelf().addClass(options.selectedClass); if (options.event) $(container).bind((options.event) + ".ui-accordion", clickHandler); }; $.ui.accordion.prototype = { activate: function(index) { // call clickHandler with custom event clickHandler.call(this.element, { target: findActive( this.options.headers, index )[0] }); }, enable: function() { this.options.disabled = false; }, disable: function() { this.options.disabled = true; }, destroy: function() { this.options.headers.next().css("display", ""); if ( this.options.fillSpace || this.options.autoheight ) { this.options.headers.next().css("height", ""); } $.removeData(this.element, "ui-accordion"); $(this.element).removeClass("ui-accordion").unbind(".ui-accordion"); } } function scopeCallback(callback, scope) { return function() { return callback.apply(scope, arguments); }; } function completed(cancel) { // if removed while animated data can be empty if (!$.data(this, "ui-accordion")) return; var instance = $.data(this, "ui-accordion"); var options = instance.options; options.running = cancel ? 0 : --options.running; if ( options.running ) return; if ( options.clearStyle ) { options.toShow.add(options.toHide).css({ height: "", overflow: "" }); } $(this).triggerHandler("change.ui-accordion", [options.data], options.change); } function toggle(toShow, toHide, data, clickedActive, down) { var options = $.data(this, "ui-accordion").options; options.toShow = toShow; options.toHide = toHide; options.data = data; var complete = scopeCallback(completed, this); // count elements to animate options.running = toHide.size() == 0 ? toShow.size() : toHide.size(); if ( options.animated ) { if ( !options.alwaysOpen && clickedActive ) { $.ui.accordion.animations[options.animated]({ toShow: jQuery([]), toHide: toHide, complete: complete, down: down, autoheight: options.autoheight }); } else { $.ui.accordion.animations[options.animated]({ toShow: toShow, toHide: toHide, complete: complete, down: down, autoheight: options.autoheight }); } } else { if ( !options.alwaysOpen && clickedActive ) { toShow.toggle(); } else { toHide.hide(); toShow.show(); } complete(true); } } function clickHandler(event) { var options = $.data(this, "ui-accordion").options; if (options.disabled) return false; // called only when using activate(false) to close all parts programmatically if ( !event.target && !options.alwaysOpen ) { options.active.parent().andSelf().toggleClass(options.selectedClass); var toHide = options.active.next(), data = { instance: this, options: options, newHeader: jQuery([]), oldHeader: options.active, newContent: jQuery([]), oldContent: toHide }, toShow = options.active = $([]); toggle.call(this, toShow, toHide, data ); return false; } // get the click target var clicked = $(event.target); // due to the event delegation model, we have to check if one // of the parent elements is our actual header, and find that if ( clicked.parents(options.header).length ) while ( !clicked.is(options.header) ) clicked = clicked.parent(); var clickedActive = clicked[0] == options.active[0]; // if animations are still active, or the active header is the target, ignore click if (options.running || (options.alwaysOpen && clickedActive)) return false; if (!clicked.is(options.header)) return; // switch classes options.active.parent().andSelf().toggleClass(options.selectedClass); if ( !clickedActive ) { clicked.parent().andSelf().addClass(options.selectedClass); } // find elements to show and hide var toShow = clicked.next(), toHide = options.active.next(), //data = [clicked, options.active, toShow, toHide], data = { instance: this, options: options, newHeader: clicked, oldHeader: options.active, newContent: toShow, oldContent: toHide }, down = options.headers.index( options.active[0] ) > options.headers.index( clicked[0] ); options.active = clickedActive ? $([]) : clicked; toggle.call(this, toShow, toHide, data, clickedActive, down ); return false; }; function findActive(headers, selector) { return selector != undefined ? typeof selector == "number" ? headers.filter(":eq(" + selector + ")") : headers.not(headers.not(selector)) : selector === false ? $([]) : headers.filter(":eq(0)"); } $.extend($.ui.accordion, { defaults: { selectedClass: "selected", alwaysOpen: true, animated: 'slide', event: "click", header: "a", autoheight: true, running: 0, navigationFilter: function() { return this.href.toLowerCase() == location.href.toLowerCase(); } }, animations: { slide: function(options, additions) { options = $.extend({ easing: "swing", duration: 300 }, options, additions); if ( !options.toHide.size() ) { options.toShow.animate({height: "show"}, options); return; } var hideHeight = options.toHide.height(), showHeight = options.toShow.height(), difference = showHeight / hideHeight; options.toShow.css({ height: 0, overflow: 'hidden' }).show(); options.toHide.filter(":hidden").each(options.complete).end().filter(":visible").animate({height:"hide"},{ step: function(now) { var current = (hideHeight - now) * difference; if ($.browser.msie || $.browser.opera) { current = Math.ceil(current); } options.toShow.height( current ); }, duration: options.duration, easing: options.easing, complete: function() { if ( !options.autoheight ) { options.toShow.css("height", "auto"); } options.complete(); } }); }, bounceslide: function(options) { this.slide(options, { easing: options.down ? "bounceout" : "swing", duration: options.down ? 1000 : 200 }); }, easeslide: function(options) { this.slide(options, { easing: "easeinout", duration: 700 }) } } }); })(jQuery); A: try this: jQuery('#navigation > li').mouseout(function(){ jQuery('#navigation').accordion("activate",false); }); also, for future compatibility, you should change jQuery().ready(... to jQuery(document).ready(... A: I think this is what you are looking for. Check out this fiddle // simple accordion with mouseover event jQuery('#navigation').accordion({ active: false, header: '.head', navigation: true, event: 'mouseover', fillSpace: true, animated: 'easeslide', collapsible: true }); $('#navigation').mouseleave(function(){ $( "#navigation" ).accordion({ active: false}); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7506331", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Center a * list with a left float *'s with CSS I have to reproduce a menu like this: +----------------------------------------------------------------------------+ Option 1 | Option 2 | Option 3 | Option 4 | Option 5 +----------------------------------------------------------------------------+ But actually I have this: +----------------------------------------------------------------------------+ Option 1 | Option 2 | Option 3 | Option 4 | Option 5 +----------------------------------------------------------------------------+ My code: <ul> <li>Option 1</li> <li>Option 2</li> <li>Option 3</li> <li>Option 4</li> <li>Option 5</li> </ul> My actual css for that code is: ul { list-style: none outside none; margin:0; padding: 0; } li { float: left; margin: 0 10px; } How I can do it? PD: IE7 alternative if possible. Thank you in advance! A: Use display: inline in li and text-align: center in ul. ul { list-style: none outside none; margin:0; padding: 0; text-align: center } li { display: inline; margin: 0 10px; } Example: http://jsfiddle.net/ravan/gh29g/ A: Use this code for the lis instead: li { margin: 0 10px; display: inline; } And center your uls' contents: ul { list-style: none outside none; margin:0; padding: 0; text-align: center; } A: Just change the li's display to inline-block; and add a text-align:center to the ul See demo: http://jsfiddle.net/adardesign/6RZL4/ A: Making li items display:inline and list text-align:center will solve the problem in this case: ul { list-style: none outside none; margin:0; padding: 0; border:1px solid #f33; text-align:center;} li {display:inline; margin: 0 10px; border:1px solid #ccc; } Fiddle: http://jsfiddle.net/mohsen/rzfPW/ But if your list items had more stuff in it(like menu items to show when mouse hover) then using display:inline is not good solution. because then the item is not an inline element. You can do display:block and still have them aligned in center with float:left and having width and margin calculated by percent: ul { list-style: none outside none; margin:0; padding: 0; border:1px solid #f33; text-align:center; padding:3px 0; overflow:hidden;} li {display:block; width:16%; float:left; margin: 0 2%; background:yellow} fiddle: http://jsfiddle.net/mohsen/rzfPW/1/ Take note using percents and pixels(probably for borders) in your css will cause errors A: Add padding: 0 10px; on the li This some what centers the options - just play around with the padding until you are happy with it
{ "language": "en", "url": "https://stackoverflow.com/questions/7506333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Handler to show the countdown timer is not reliable I am developing an App where I show the countdown timer. To countdown the time I am using Handler class. Once the countdown timer reaches certain time the Alarm goes off. My problem is as below, Initially I show the timer time as 04:00:00. Once it reaches 00:00:00 then the Alarm goes off. The Alarm code is working fine. But the timer display is not reliable. It works fine until I keep the App open. If I close the App (using Home or Back) or lock the device and open App again then the timer shown is not the correct one (delaying a lot, but still alarm works on-time). (But it works sometimes very fine under the same scenario). But whenever I ping the device to the system for checking the Log in eclipse that time all works fine!!!!!!! 1. I want to know whether I am using the Handler properly or not 2. (or) Is going out of the App or locking the device causing the problem Below is my Handler code, Handler digiHandler; // Method to initialize the time and define the Handler public void initialize(int hourstime,int mintime,int sectime){ hour = hourstime; min = mintime; sec = sectime; digiHandler = new Handler(); handleRunnable = new Runnable(){ public void run(){ updateTimes(); } }; } public void startUpdateTheread(){ digiHandler.postDelayed(handleRunnable, UPDATEDELAY); } // Method to update the timer times private void updateTimes(){ timerText = String.format(timerFormat,hour,min,sec ); ------------------------- ------------------------- -- code for incrementing the time --- -------------------------- -------------------------- -------------------------- startUpdateTheread(); } Please give the suggestions Thanks Edit: When I observed the log it shows that to countdown 1 second of timer sometimes it is taking 1 minute time. The log is as below, 09-21 21:09:18.965: DEBUG/DigitalTimer(7656): timerText**:04:22:54 ****long difference here**** 09-21 21:10:19.308: DEBUG/DigitalTimer(7656): timerText**:04:22:53 .................................................................................. .................................................................................. .................................................................................. 09-21 21:10:23.314: DEBUG/DigitalTimer(7656): timerText**: 04:22:49 **--long difference here ---** 09-21 21:11:22.604: DEBUG/DigitalTimer(7656): timerText**:04:22:48 It is happening always. So I can rule out that locking/coming out of an App is causing the problem. Seems I need to tweak the Handler part of the code. A: The problem is that if the activity dies, then so does the thread it spawned, I recommend creating a service to handle this since such timers can be long i imagine (over 4 minutes) and in that time, you need the application to not die. take a look at http://developer.android.com/reference/android/app/Service.html and let me know if that seems like a good enough solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506334", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MonoDroid Bluetooth I have been working with Monodroid for a few days and still can't figure out how to send a command through Bluetooth. This is my scenario: I have a Tablet/Cellphone working with Android 2.1+ and need to send and receive data to a Bluetooth printer (in bytes). What i managed so far: using Android.Bluetooth; // library necessary BluetoothAdapter bth = BluetoothAdapter.DefaultAdapter; if (!bth.IsEnabled) bth.Enable(); ICollection<BluetoothDevice> bthD = bth.BondedDevices; foreach (BluetoothDevice d in bthD) { if (d.Name == "DPP-350") { Java.Util.UUID UUID = Java.Util.UUID.FromString("00001101-0000-1000-8000-00805F9B34FB"); // Get the BLuetoothDevice object BluetoothSocket s = d.CreateRfcommSocketToServiceRecord(UUID); s.Connect(); // Try to send command ... s.Close() } } The program asks for the pairing info, with is done correctly. I have tried many ways to send the command: // the command // Self_Test = Chr(27) + Chr(84) = ESC T byte[] dBytes = System.Text.Encoding.GetEncoding(1252).GetBytes(Self_Test); // wont work new Java.IO.ObjectOutputStream(s.OutputStream).Write(dBytes); // wont work System.IO.Stream st = s.OutputStream; if (st.CanWrite) { st.Write(dBytes, 0, dBytes.Length); st.Flush(); } // wonk work s.OutputStream.Write(dBytes, 0, dBytes.Length); s.OutputStream.Flush(); No error is raised. I'm running out of options here... Thanks in advance! A: I know this is a very old thread, but I wanted to post a reply so others will know the answer. I too searched hard with no luck. s.OutputStream.BeginWrite(buffer, 0, buffer.Length,new AsyncCallback(delegate {}), State.Connected); Thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506335", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to import multiple Excel columns into single SQL Server column? We import a lot of data files (mostly Excel, sometimes CSV) from different sources into SQL Server databases. The data files have some common fields (name, address, etc.) and usually other fields - some we need/use and some that we don't need. How could I import all the data in a file - inserting the common/required fields into the relevant columns but also merging the other remaining columns into a single column (text or varchar(max))? Is this possible? I don't mind what version of Excel/SQL Server. So I might receive a source file such as FirstName, LastName, AddressLine1, City, ColumnE, ColumnF, DateColumn, ColumnH And this is stored in the SQL Server as FirstName nvarchar(25) LastName nvarchar(25) AddressLine1 nvarchar(50) City nvarchar(30) OtherData nvarchar(max) Of course the OtherData column needs to contain some delimiter to identify the Excel columns imported. We only need to use the "common" columns, but when we export the data (which typically is only a subset of the original rows) we could more easily include the OtherData than creating customised tables for every different data file or merging back with Excel. EDIT: I can achieve this by adding lots of extra columns to the data-file that act as a custom delimiter, then use BULK INSERT, but that's quite time-consuming. A: As a rough idea, if you know the tab names in excel, you can use C# and the OLE DB/JET 12 driver to read the data into a dataset (basically SELECT * FROM [tabname]). CSV can be loaded much simpler. At that point, it's a matter of punching it into the database. I miht be able to scratch out some psuedocode this evening if you're interested in that sort of approach.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506339", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: VB6 pass an object variable back to opening form How do I do this? I thought that I could pass the form as a variable to the child form. Then the child form could set a variable (as public property) on the parent form. But I get some weird "function or interface marked as restricted" error. Whats the way to do this in vb6?? Is it just a case of making the object a global variable? thanks. A: Most often when you create a Form in a Project, you make use of the global predeclared instance anyway. So in such cases you have no need to pass anything as a parameter and no extra global reference to declare and set. Just use the one you get "for free." From your Form2 you can make use of Form1 with no extra coding. That goes out the window (!) if you are doing anything more complex though, like wanting to touch more than one different Form in some procedure. There you'd pass the Form as an argument.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506341", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to display leading zeros programmatically this field has leading zeros. newSheet.Cells[i + 2, 5] = drugorder.NDC; the code is seeing it when it looks up the NDC description in the SQL Server table. But it doesnt display when we write this col to the new sheet in Excel. how can we display the leading zeros? A: Did you try drugorder.NDC.ToString("0000") ? A: You can set the number format of the cells in question to be Text. This will preserve the leading zeroes. Take the Range object in question and set its NumberFormat property to be @
{ "language": "en", "url": "https://stackoverflow.com/questions/7506342", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Quering dates back 2 years I need to add a couple and statements to my WHERE clause. I need to get data from today back 2 years. I'm not sure how to write that in SQL. I got every thing else though, so it's at the end of the code: FUNCTION summarize_item_search_data (p_obj_code IN VARCHAR2, p_val2 IN VARCHAR2, p_sac IN NUMBER, p_job_type_id IN NUMBER, p_sup IN NUMBER) RETURN sys_refcursor IS stmt VARCHAR2(4000); result_cur sys_refcursor; BEGIN OPEN result_cur FOR SELECT DISTINCT jp.id, jp.row_top.mwslin AS mwslin, jp.obj_code, jp.jobload_year, jp.row_top.fiscal_year AS fiscal_year, val1s.sac, val2s.val2, val1s.val1, DECODE( jp.row_top.val1_id, NULL, jp.row_top.nomenclature ,val1s.nomenclature) AS nomenclature, jp.row_top.sup AS sup FROM schedules sch, job_plans JP, master_val1 val1s, master_val2 val2s, TABLE(val2s.group_id) (+) ntab, groups pgds WHERE -- stmt := stmt || ' AND ''' || p_year || ''' = ntab.fiscal_year(+)'; (val1s.sac = p_sac OR p_sac IS NULL) AND (UPPER(val2s.val2) LIKE UPPER(p_val2) OR p_val2 IS NULL) AND (UPPER(jp.obj_code) LIKE UPPER(p_obj_code) OR p_obj_code IS NULL) AND (jp.row_top.sup <= p_sup OR p_sup IS NULL) AND (jp.row_top.job_type_id = p_job_type_id OR p_job_type_id IS NULL) AND ntab.group_id = pgds.id(+) AND jp.row_top.val1_id = val1s.id(+) AND val1s.val2_id = val2s.id(+) AND jp.jobload_year > AND fiscal_year > RETURN result_cur; END summarize_item_search_data; A: AND jp.jobload_year > ADD_MONTHS(CURRENT_DATE, -24) AND fiscal_year > ADD_MONTHS(CURRENT_DATE, -24) I see those fields aren't datetime, so that won't work. You would need to convert them to datetime, or convert to integer and compare by year alone. Going with the first option, you could try: AND TO_DATE('1-1-'||jp.jobload_year) > ADD_MONTHS(CURRENT_DATE, -24) AND TO_DATE('1-1-'||fiscal_year) > ADD_MONTHS(CURRENT_DATE, -24) Although it's not very dynamic. Could wait for a better solution. A: @Shredder's solution is perfectly functional, but it isn't sargable. Even if there is no applicable index today, designing queries so that they can take advantage of indexes that may be created in the future is a good practice (assuming that it doesn't add significant complexity): AND jp.jobload_year > TO_CHAR(ADD_MONTHS(CURRENT_DATE, -24),'YYYY') AND fiscal_year > TO_CHAR(ADD_MONTHS(CURRENT_DATE, -24),'YYYY')
{ "language": "en", "url": "https://stackoverflow.com/questions/7506344", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Returning Azure BLOB from WCF service as a Stream - Do we need to close it? I have a simple WCF service that exposes a REST endpoint, and fetches files from a BLOB container. The service returns the file as a stream. i stumbled this post about closing the stream after the response has been made : http://devdump.wordpress.com/2008/12/07/disposing-return-values/ This is my code: public class FileService { [OperationContract] [WebGet(UriTemplate = "{*url}")] public Stream ServeHttpRequest(string url) { var fileDir = Path.GetDirectoryName(url); var fileName = Path.GetFileName(url); var blobName = Path.Combine(fileDir, fileName); return getBlob(blobName); } private Stream getBlob(string blobName) { var account = CloudStorageAccount.FromConfigurationSetting("ConnectingString"); var client = account.CreateCloudBlobClient(); var container = client.GetContainerReference("data"); var blob = container.GetBlobReference(blobName); MemoryStream ms = new MemoryStream(); blob.DownloadToStream(ms); ms.Seek(0, SeekOrigin.Begin); return ms; } } So I have two question : * *Should I follow the pattern mentioned in the post ? *If I change my return type to Byte[], what are Cons/Pros ? ( My client is Silverlight 4.0, just in case it has any effect ) A: I'd consider changing your return type to byte[]. It's tidier. Stream implements IDisposable, so in theory the consumer of your method will need to call your code in a using block: using (var receivedStream = new FileService().ServeHttpRequest(someUrl)) { // do something with the stream } If your client definitely needs access to something that Stream provides, then by all means go ahead and return that, but by returning a byte[] you keep control of any unmanaged resources that are hidden under the covers. A: OperationBehaviorAttribute.AutoDisposeParameters is set to TRUE by default which calls dispose on all the inputs/outputs that are disposable. So everything just works. This link : http://devdump.wordpress.com/2008/12/07/disposing-return-values/ explains how to manually control the process.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506350", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Are suo (solution option) files portable? or tied a user or to that particular instance of the solution? In Visual studio 2008 -- For my particular project, I only care about a subset of a solution. I handle this by unloading the projects I don't need. I know these settings are saved in suo. So what I'd like to do is save off the suo file with these settings for later use so that when I (or someone else on my team) checks out the code, instead of seeing the entire solution, they can apply this suo file and just the subset they care about without having to manually unload each project. Is this possible, or are suo files tied to a specific user or directory or some such? How portable are these files? A: I checked out a second copy of my solution and applied a suo file from another checked out copy. The projects unloaded in the original were also unloaded in the newly checked out copy after applying the original suo. So the suo seems to be somewhat transplantable to different instances of your solution. Still haven't prove definitively whether suo is tied to a specific user account and I assume it won't work if your solution file gets too far from the solution originally used to create the suo. A: When your team mates check-out your version of the .suo they will overwrite a lot of other options, too. For a list see: my answer to another stackoverflow question. Maybe you should just create a second solution, that only contains the subset of projects.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506353", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: eclipse mylyn with redmine Is it possible to connect mylyn to redmine without rest support in redmine? A: * *there is a link http://download.eclipse.org/mylyn/incubator/3.8 that can be used in Eclipse. for Eclipse indigo : * *Help -> Install New Software -> Add -> use the link above for URL *there should be plugin to check off : Mylyn Incubator -> Mylyn Task Connector:Web Templates (Advanced)(Incubation). Version = 3.8.0.I20120414-0402 *after installing it, i was able to follow steps outlined in http://www.redmine.org/projects/redmine/wiki/HowTo_Mylyn ( the section 'Using the generic web repository connector' ). *there is also a half decent video on Youtube :) A: If you are using Eclipse indigo then use the update site: (As of 09/16/2012) http://download.eclipse.org/mylyn/incubator/3.8 install "Mylyn Tasks Connector: Web Templates (Advanced)" and follow the instructions at the link mikalv posted above. It looks like the incubator links is changing as Eclipse versions go up. It looks like the best way to find out the update url is to check Generic Web Templates Connector section of Mylyn User Guide wiki They provide the up to date link to mylyn download site where you can find the update url for the incubator.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506357", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Wince Socket exception on asynchronous HTTP request I am writing a WinCE app in C# that makes an HTTP POST to an APACHE server residing on my network. Because of some network issues (I am guessing), I get the following exception in the managed code System.Net.Sockets.SocketException occurred Message="A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond" ErrorCode=10060 NativeErrorCode=10060 StackTrace: at System.Net.Sockets.Socket.ConnectNoCheck(EndPoint remoteEP) at System.Net.Sockets.Socket.Connect(EndPoint remoteEP) at System.Net.Connection.doConnect(IPEndPoint ep) at System.Net.Connection.connect(Object ignored) at System.Threading.ThreadPool.WorkItem.doWork(Object o) at System.Threading.Timer.ring() This exception isn't always thrown, but when it is thrown, my app fails to connect to the server AT ALL. Repeated connection attempts don't help in reconnecting either. The only thing that helps is closing and re-deploying the app. I can't catch the exception because its inside of managed code. Is there any way to circumvent this and close all socket connections to my server and re-initialize them? Is there something I am doing wrong? A: The exception message looks a bit misleading ("connection attempt failed because the connected party") but I think it means your hardware is communicating with the server, but the server is not accepting the connection on the TCP level. A problem I could think of is "hanging" connections, causing the server to reach the maximum number of concurrent connections and to stop accepting new ones. Although it's just a guess, you might want to check the apache log if you can to see if you can find out if the server reports anything, and perhaps try restarting apache as soon as the problem occurs again. If that helps, you still need to find the cause of course.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506361", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Should I test the private functions of a Javascript plugin? I am trying to write test driven Javascript. Testing each function, I know, is crucial. But I came to a stumbling block, in that the plugin which I am writing needs to have some private functions. I cannot peek into how they are functioning. What would I need to do if I want to keep my code well tested without changing the structure of it too much? (I am ok with exposing some API, though within limits.) I am using sinon, QUnit, and Pavlov. A: If you are doing test driven development (as suggested by the tags) each line of production code is first justified by failing test case. In other words the existence of each and every line of your production code is implicitly tested because without it some test must have failed. That being said you can safely assume that private function/lambda/closure is already tested from the definition of TDD. If you have a private function and you are wondering how to test it, it means you weren't doing TDD on the first place - and now you have a problem. To sum up - never write production code before the test. If you follow this rule, every line of code is tested, no matter how deep it is.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506364", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Redirect everything in a subfolder from one domain to another using .htaccess I have a website migrated to a new domain. what's the best way to 301 redirect everything from: "domain1.com/folder/" to "domain2.com/folder/" in .htaccess? A: As simple as Redirect 301 /folder/ http://domain2.com/folder/ This needs to be placed on .htaccess in website root folder of the domain1.com.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506366", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Studying and understanding how Google AdSense works behind the scenes I would like to learn how Google AdSense works in the sense of understanding for an example how that javascript we put on a page loads an iframe (is it an iframe ?) which checks the words on a page and then sends those words and gets back some ads. Does anyone know any good tutorials on this ? I'm not interested in knowing how to use google adsense or what's the logic behind it (so this and this do not answer my question) A: I don't think the JavaScript does send back the page contents. I believe that they use a separate crawler (different to their Google Search crawler) that scans your pages for keywords. When AdSense is added to a page it tells Google the URL and then the crawler scans the page later. That is why there is a delay between putting the AdSense on the page, and getting relevant adverts.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506367", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Remote and local printing from a C# ASP.NET application My situation involves an ASP.NET application that I have written which should remotely print orders, as well as print a local copy for the person creating the order on the local client machine. The process works like this: once an order has been created in previous pages and is submitted into the system, the order information is first permanently stored into an Oracle database table. The application then carries the user to a printer-friendly order page with the final order displayed and ready to print. An order page consists of some title text at the top, places for signatures and dates, and finally, a GridView object containing the information about the order (item category, item subcategory, and quantity for each ordered item). Once this page has finished loading and is ready for printing, I need the system to do two things: * *Print the order information page to the default local printer on the client computer, or else call up the print dialog to allow the user to print the order information. *Print the order information to a remote printer (with a known, static IP address) located elsewhere on our network where the orders get processed. Printing to the local machine is easy to figure out, of course. I had intended to simply call the default print dialog and allow the user to print from there, or to do some similar function to allow the webpage to print locally. The difficulty comes in figuring out how to print to the remote computer. All I have available to me to specify that printer to the system is its static IP address. I don't have the shared name of the printer. Given this information, is it possible to have the webpage print automatically on the remote printer where the orders get processed? If so, what do I need to use to do it? Also, if anyone has some sample code that might help get me started (in either VB or C#, although this project's back-end code is in C#), it would be extremely appreciated. Thanks! A: I've once implemented such a thing but the user that's running your ASP.net application should have enough rights to print (which it doesn't most of the time for obvious reasons). What I had done in order to fix this is create a client web service that accepts the document to print and sends that (it is installed on a machine in the same domain as the printer) to the printer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506371", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Reordering buttons in UI as the size is adjusted I'm developing a UI using wxWidgets. I'm working with Visual Studio 2010 C++ Express. My UI consists of 7 vertical grids and 1 horizontal grid which envelopes this 7. In each of these 7 grids, I have 2 or 3 bitmap buttons which are relatively ordered according to each other and neighbor grid boundaries. I set the main horizontal grid as sizer to the panel. I want that these 7 grids always take place in the "middle" of my panel; which means: With every size adjustment, their coordinates should be recalculated and buttons should move to their newly calculated locations. Is it possible to do this size adjustment with wxWidgets? I checked on the documentation and samples, but I couldn't find a simple example for my problem. Thanks. A: Write a resize event handler which recalculates the positions of the buttons and moves them to their new locations. void myWindow::OnResize( wxSizeEvent& event ) { wxSize sz = event.GetSize(); // calculate new positions ... // move buttons to new locations myButton->Move( x, y )' }
{ "language": "en", "url": "https://stackoverflow.com/questions/7506374", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make a call via my application on Android? I have an Android application that can make calls via internet or " VoIP ". So, I need the telephony API to put my application as a suggestion when a user dials-up a number ! any suggestions on how to do that ?! A: You need to register an intent filter in the manifest for your dialer activity: <intent-filter> <action android:name="android.intent.action.VIEW" /> <action android:name="android.intent.action.DIAL" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter>
{ "language": "en", "url": "https://stackoverflow.com/questions/7506375", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ajax call getting canceled by browser I am using the Prototype JS framework to do Ajax calls. Here is my code: new Ajax.Request( '/myurl.php', {method: 'post', postBody: 'id='+id+'&v='+foo, onSuccess: success, onFailure: failed} ); function success(ret) { console.log("success",ret.readyState, ret.status); } function failed(ret) { console.log("failed",ret.readyState, ret.status); } Most of the time, this works fine and the success function is called with a status code of 200. About 5% of the time on Safari the success function is called with a status code of 0. In this case, when I look in the Network tab of the web inspector, the ajax call is listed with a status of "canceled". I can confirm with server logs, that the request never hit the server. It's as if the ajax request was immediately canceled without even trying to connect to the server. I have not found any reliable way to reproduce this, it seems to be random. I do it 20 times and it happens once. Does anyone know what would cause the ajax call to get canceled or return a status code of 0? A: The cause may be the combination of http server and browser you are using. It doesn't seems like an error of the PrototypeJS library. Multiple sources states that keep-alive parameter of the HTTP connection seems to be broken in Safari (see here, here or here). On Apache, they recommend adding this to the configuration: BrowserMatch "Safari" nokeepalive (Please check the appropriate syntax in your server documentation). If Safari handles badly HTTP persistent connections with your server, it may explain what you experiences. If it's not too complex for you, I would try another HTTP server, there are plenty available on every OS. We lack a bit of information to answer fully your answer, though. The server issue is a lead but there may be others. It would be nice to know if it does the same thing in other browsers (Firefox with Firebug will display this kind of information, Chrome, Opera and IE have development builtin toolboxes). Another valid question would be how often you execute this AJAX request per second (if relevant). A: I know this is an old topic, but I wanted to share a solution for Safari that might save others some time. The following line really solved all problems: BrowserMatch "^(?=.*Safari)(?=.*Macintosh)(?!.*Chrom).*" nokeepalive gzip-only-text/html The regex makes sure only Safari on Mac is detected, and not Mobile Safari and Chrome(ium) and such. Safari for Windows is also not matched, but the keepalive problem seems to be a Mac-Safari combination only. In addition, some Safari versions do not handle gzipped css/js well. All our symptoms of our site crashing or CSS not completley loading in different versions of Safari which caused me to nearly pull my hair out (Safari really is the new IE) have been solved for us with this Apache 'configuration hack'.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506376", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How do I get a YouTube FLV URL? Looking through the site, every question uses an outdated method. How do the YouTube FLV downloader websites/applications do it? I am trying to do this in PHP but the theory or steps to do it will suffice, thanks. A: You might want to take a look at how youtube-dl downloads the files. As YouTube changes, that program does seem to get updated rather quickly. A: As mentioned in other posts, you may want to look at our code in youtube-dl (or in the code of the Firefox extension called FlashVideoReplacer). In the particular case of youtube-dl, the "real work" is done in the subclasses of InformationExtractor and it hard to give a "stable" answer, as the layout of such sites changes constantly. There are some pieces of the information that are not dynamic, such as, for instance, the uploader of the video, the title, the date of upload, and, most importantly, the identifier of the video (a 11-character string). For the dynamic parts, what can be said about such tools is that, essentially, the URLs generated by such videos are dynamically generated and you need to perform some back-and-forth communication with the server. It is important to have in mind that what such sites can (and do) take into consideration depend on a number of parameters, including: the cookies that you have already received---as the case for HTML5 videos, your geolocation---for regional control, your age--for "strong" material, your language/locale---for showing content tailored to you, etc. youtube-dl uses a regular expression to extract the video ID from the URL that you give and, then, uses a "normalized", typical URL as used from the United States, from which to proceed. Some of the dynamic data to be gathered includes: * *some time-stamp (the expire, and fexp parts of the final URL) *the cookies sent to the browser *the format in which we want to download the video (the itag part of the final URL) *throttling information (the algorithm, burst, factor) *some hashes/tokens used internally by them (e.g., the signature part of the final URL) Some of the information listed above were once not required, but now they are (in particular, the cookies that they send you). This means that the information listed above is very likely to become obsolete, as the controls become stricter. You can see some of the work (with respect to the cookies) that I did in this regard in the implementation of an external backend to use an external downloader (a "download accelerator") with what youtube-dl extracts. Discloser: I have committed some changes to the repository, and I maintain the youtube-dl package in Debian (and, as a side effect, in Ubuntu). A: Youtube doesn't store FLV files, they compile your video into a SWF object. Those videos need to be either extracted or converted to FLV in order to get the FLV. http://www.youtube.com/v/videoid ex: http://www.youtube.com/watch?v=C6nRb45I3e4 becomes http://www.youtube.com/v/C6nRb45I3e4 From there, you need to convert the SWF into an flv, which can be done with ffmpeg. A: If you really want to get an url of youtube video in flv or mp4 mode then use "YouTube Downloader - Version: 5.0" in Chrome you can right click on download button and copy path. ![You can get url of any format from this button][1] http://i.stack.imgur.com/AFUWr.jpg (see this url due to i can't upload image at this time) You can click on this button and copy url from "chrome://downloads/" I think this may help you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to create Android Facebook Key Hash? I do not understand this process at all. I have been able to navigate to the folder containing the keytool in the Java SDK. Although I keep getting the error openssl not recognised as an internal or external command. The problem is even if I can get this to work, what would I do and with what afterwards? A: Since API 26, you can generate your HASH KEYS using the following code in KOTLIN without any need of Facebook SDK. fun generateSSHKey(context: Context){ try { val info = context.packageManager.getPackageInfo(context.packageName, PackageManager.GET_SIGNATURES) for (signature in info.signatures) { val md = MessageDigest.getInstance("SHA") md.update(signature.toByteArray()) val hashKey = String(Base64.getEncoder().encode(md.digest())) Log.i("AppLog", "key:$hashKey=") } } catch (e: Exception) { Log.e("AppLog", "error:", e) } } A: Easy way By using this website you can get Hash Key by Converting SHA1 key to Hash Key for Facebook. A: That's how I obtained my: private class SessionStatusCallback implements Session.StatusCallback { @Override public void call(Session session, SessionState state, Exception exception) { if (exception != null) { new AlertDialog.Builder(FriendActivity.this) .setTitle(R.string.login_failed_dialog_title) .setMessage(exception.getMessage()) .setPositiveButton(R.string.ok_button, null) .show(); } So when you re trying to enter without the key, an exception will occur. Facebook put the RIGHT key into this exception. All you need to do is to copy it. A: EASY WAY -> Don't install openssl -> USE GIT BASH! keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64 The default password is "android" Most of us have Git Bash installed so this is my favorite way. A: You can simply use one line javascript in browser console to convert a hex map key to base64. Open console in latest browser (F12 on Windows, ⌥ Option+⌘ Command+I on macOS, Ctrl+⇧ Shift+I on Linux) and paste the code and replace the SHA-1, SHA-256 hex map that Google Play provides under Release Setup App signing: Hex map key to Base64 key hash > btoa('a7:77:d9:20:c8:01:dd:fa:2c:3b:db:b2:ef:c5:5a:1d:ae:f7:28:6f'.split(':').map(hc => String.fromCharCode(parseInt(hc, 16))).join('')) < "p3fZIMgB3fosO9uy78VaHa73KG8=" You can also convert it here; run the below code snippet and paste hex map key and hit convert button: document.getElementById('convert').addEventListener('click', function() { document.getElementById('result').textContent = btoa( document.getElementById('hex-map').value .split(':') .map(hc => String.fromCharCode(parseInt(hc, 16))) .join('') ); }); <textarea id="hex-map" placeholder="paste hex key map here" style="width: 100%"></textarea> <button id="convert">Convert</button> <p><code id="result"></code></p> And if you want to reverse a key hash to check and validate it: Reverse Base64 key hash to hex map key > atob('p3fZIMgB3fosO9uy78VaHa73KG8=').split('').map(c => c.charCodeAt(0).toString(16)).join(':') < "a7:77:d9:20:c8:1:dd:fa:2c:3b:db:b2:ef:c5:5a:1d:ae:f7:28:6f" document.getElementById('convert').addEventListener('click', function() { document.getElementById('result').textContent = atob(document.getElementById('base64-hash').value) .split('') .map(c => c.charCodeAt(0).toString(16)) .join(':') }); <textarea id="base64-hash" placeholder="paste base64 key hash here" style="width: 100%"></textarea> <button id="convert">Convert</button> <p><code id="result"></code></p> A: OpenSSL: You have to install that if it doesn't come preinstalled with your operating system (e.g. Windows does not have it preinstalled). How to install that depends on your OS (for Windows check the link provided by coder_For_Life22). The easiest way without fiddling around is copying that openssl.exe binary to your keytool path if you are on Windows. If you don't want to do that, you have to add it to your PATH environment variable. Then execute the command provided in the docs. keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64 Note that the argument after -keystore points to your debug keystore. This location also depends on your operating system. Should be in one of the following locations: * *Windows Vista or 7 - C:\Users\.android\debug.keystore *Windows XP - C:\Documents and Settings\.android\debug.keystore *OS X and Linux - ~/.android/debug.keystore If you did everything right, you should be prompted for a password. That is android for the debug certificate. If the password is correct the console prints a hash (somewhat random chars and numbers). Take that and copy it into the android key hash field inside the preferences of your app on facebook. To get there, go to developers.facebook.com/apps, select your app, go to Edit settings and scroll down. After that, wait a few minutes until the changes take effect. A: Run either this in your app : FacebookSdk.sdkInitialize(getApplicationContext()); Log.d("AppLog", "key:" + FacebookSdk.getApplicationSignature(this)+"="); Or this: public static void printHashKey(Context context) { try { final PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES); for (android.content.pm.Signature signature : info.signatures) { final MessageDigest md = MessageDigest.getInstance("SHA"); md.update(signature.toByteArray()); final String hashKey = new String(Base64.encode(md.digest(), 0)); Log.i("AppLog", "key:" + hashKey + "="); } } catch (Exception e) { Log.e("AppLog", "error:", e); } } And then look at the logs. The result should end with "=" . Solution is based on here and here . A: so easy find sha1 of your android project and paste on this website tomeko for get sha1 just // vscode and my cmd project-name/cd android && ./gradlew signingReport // other project-name/cd android && ./gradlew signingReport A: Here is complete details (For Windows) 1. Download OpenSSl either 3rd or 4th (with e will work better) based on your system 32bit or 64bit . 2. Extract the downloaded zip inside C directory 3. Open the extracted folder up to bin and copy the path ,it should be some thing like C:\openssl-0.9.8k_X64\bin\openssl (add \openssl at end) 4. (Get the path to the bin folder of Jdk ,if you know how,ignore this ) . Open android studio ~file~Project Structure(ctrl+alt+shift+s) , select SDK location in left side panel ,copy the JDK location and add /bin to it So final JDK Location will be like C:\Program Files\Android\Android Studio\jre\bin we are following this method to get Jdk location because you might use embedded jdk like me now you have OpenSSl location & JDK location 5. now we need debug keystore location , for that open C~>Users~>YourUserName~>.android there should be a file name debug.keystore ,now copy the path location ,it should be some thing like C:\Users\Redman\.android\debug.keystore 6. now open command prompt and type command cd YourJDKLocationFromStep4 in my case cd "C:\Program Files\Android\Android Studio\jre\bin" 7. now construct the following command keytool -exportcert -alias androiddebugkey -keystore YOURKEYSTORELOCATION | YOUROPENSSLLOCATION sha1 -binary | YOUROPENSSLLOCATION base64 in my case the command will look like keytool -exportcert -alias androiddebugkey -keystore "C:\Users\Redman\.android\debug.keystore" | "C:\openssl-0.9.8k_X64\bin\openssl" sha1 -binary | "C:\openssl-0.9.8k_X64\bin\openssl" base64 now enter this command in command prompt , if you did ever thing right you will be asked for password (password is android) Enter keystore password: android thats it ,you will be given the Key Hash , just copy it and use it For Signed KeyHash construct the following Command keytool -exportcert -alias YOUR_ALIAS_FOR_JKS -keystore YOUR_JKS_LOCATION | YOUROPENSSLLOCATION sha1 -binary | YOUROPENSSLLOCATION base64 enter your keystore password , If you enter wrong password it will give wrong KeyHash NOTE If for some reason if it gives error at some path then wrap that path in double quotes .Also Windows power shell was not working well for me, I used git bash (or use command prompt) . example keytool -exportcert -alias androiddebugkey -keystore "C:\Users\Redman\.android\debug.keystore" | "C:\openssl-0.9.8k_X64\bin\openssl" sha1 -binary | "C:\openssl-0.9.8k_X64\bin\openssl" base64 A: If you have already uploaded the app to Play store you can generate Hash Key as follows: * *Go to Release Management here *Select Release Management -> App Signing *You can see SHA1 key in hex format App signing certificate. *Copy the SHA1 in hex format and convert it in to base64 format, you can use this link do that without the SHA1: part of the hex. *Go to Facebook developer console and add the key(after convert to base 64) in the settings —> basic –> key hashes. A: Download open ssl: Then add openssl\bin to the path system variables: My computer -> properties -> Advanced configurations -> Advanced -> System variables -> under system variables find path, and add this to its endings: ;yourFullOpenSSLDir\bin Now open a command line on your jdk\bin folder C:\Program Files\Java\jdk1.8.0_40\bin (on windows hold shift and right click -> open command line here) and use: keytool -exportcert -alias keystorealias -keystore C:\yourkeystore\folder\keystore.jks | openssl sha1 -binary | openssl base64 And copy the 28 lenght number it generates after giving the password. A: You can get all your fingerprints from https://console.developers.google.com/projectselector/apis/credentials And use this Kotlin code to convert it to keyhash: fun main(args: Array<String>) { listOf("<your_production_sha1_fingerprint>", "<your_debug1_sha1_fingerprint>", "<your_debug2_sha1_fingerprint>") .map { it.split(":") } .map { it.map { it.toInt(16).toByte() }.toByteArray() } .map { String(Base64.getEncoder().encode(it)) } .forEach { println(it) } } A: this will help newbees also. just adding more details to @coder_For_Life22's answer. if this answer helps you don't forget to upvote. it motivates us. for this you must already know the path of the app's keystore file and password for this example consider the key is stored at "c:\keystorekey\new.jks" 1. open this page https://code.google.com/archive/p/openssl-for-windows/downloads 2. download 32 or 64 bit zip file as per your windows OS. 3. extract the downloaded file where ever you want and remember the path. 4. for this example we consider that you have extracted the folder in download folder. so the file address will be "C:\Users\0\Downloads\openssl-0.9.8e_X64\bin\openssl.exe"; 5. now on keyboard press windows+r button. 6. this will open run box. 7. type cmd and press Ctrl+Shift+Enter. 8. this will open command prompt as administrator. 9. here navigate to java's bin folder: if you use jre provided by Android Studio you will find the path as follows: a. open android studio. b. file->project structure c. in the left pane, click 'SDK location' d. in the right pane, below 'JDK location' is your jre path. e. add "\bin" at the end of this path as the file "keytool.exe", we need, is inside this folder. for this example i consider, you have installed java separately and following is the path "C:\Program Files\Java\jre-10.0.2\bin" if you have installed 32bit java it will be in "C:\Program Files (x86)\Java\jre-10.0.2\bin" 10. now with above paths execute command as following: keytool -exportcert -alias androiddebugkey -keystore "c:\keystorekey\new.jks" | "C:\Users\0\Downloads\openssl-0.9.8e_X64\bin\openssl.exe" sha1 -binary |"C:\Users\0\Downloads\openssl-0.9.8e_X64\bin\openssl.exe" base64 *You will be asked for password, give the password you have given when creating keystore key. !!!!!! this will give you the key errors: if you get: --- 'keytool' is not recognized as an internal or external command --- this means that java is installed somewhere else. A: Here is what you need to do - Download openSSl from Code Extract it. create a folder- OpenSSL in C:/ and copy the extracted code here. detect debug.keystore file path. If u didn't find, then do a search in C:/ and use the Path in the command in next step. detect your keytool.exe path and go to that dir/ in command prompt and run this command in 1 line- $ keytool -exportcert -alias androiddebugkey -keystore "C:\Documents and Settings\Administrator.android\debug.keystore" | "C:\OpenSSL\bin\openssl" sha1 -binary |"C:\OpenSSL\bin\openssl" base64 it will ask for password, put android that's all. u will get a key-hash A: to generate your key hash on your local computer, run Java's keytool utility (which should be on your console's path) against the Android debug keystore. This is, by default, in your home .android directory). On OS X, run: keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64 On Windows, use:- keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%\.android\debug.keystore | openssl sha1 -binary | openssl base64 hope this will help you Ref - developer facebook site A: For Linux and Mac Open Terminal : For Debug Build keytool -exportcert -alias androiddebugkey -keystore debug.keystore | openssl sha1 -binary | openssl base64 You will find debug.keystore in the ".android" folder. Copy it and paste onto the desktop and run the above command. For release Build keytool -exportcert -alias <aliasName> -keystore <keystoreFilePath> | openssl sha1 -binary | openssl base64 NOTE : Make sure that in both cases it asks for a password. If it does not ask for a password, it means that something is wrong in the command. Password for debug.keystore is "android" and for release you have to enter password that you set during create keystore. A: Just run this code in your OnCreateView Or OnStart Actvity and This Function Return you Development Key Hash. private String generateKeyHash() { try { PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES); for (Signature signature : info.signatures) { MessageDigest md = (MessageDigest.getInstance("SHA")); md.update(signature.toByteArray()); return new String(Base64.encode(md.digest(), 0)); } }catch (Exception e) { Log.e("exception", e.toString()); } return "key hash not found"; } A: There is a short solution too. Just run this in your app: FacebookSdk.sdkInitialize(getApplicationContext()); Log.d("AppLog", "key:" + FacebookSdk.getApplicationSignature(this)); A longer one that doesn't need FB SDK (based on a solution here) : public static void printHashKey(Context context) { try { final PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES); for (android.content.pm.Signature signature : info.signatures) { final MessageDigest md = MessageDigest.getInstance("SHA"); md.update(signature.toByteArray()); final String hashKey = new String(Base64.encode(md.digest(), 0)); Log.i("AppLog", "key:" + hashKey + "="); } } catch (Exception e) { Log.e("AppLog", "error:", e); } } The result should end with "=" . A: Please try this: public static void printHashKey(Context pContext) { try { PackageInfo info = pContext.getPackageManager().getPackageInfo(pContext.getPackageName(), PackageManager.GET_SIGNATURES); for (Signature signature : info.signatures) { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(signature.toByteArray()); String hashKey = new String(Base64.encode(md.digest(), 0)); Log.i(TAG, "printHashKey() Hash Key: " + hashKey); } } catch (NoSuchAlgorithmException e) { Log.e(TAG, "printHashKey()", e); } catch (Exception e) { Log.e(TAG, "printHashKey()", e); } } A: step 1->open cmd in your system step 2->C:\Program Files\Java\jdk1.6.0_43\bin> Step 3->keytool -list -v -keystore C:\Users\leon\.android\debug.keystore -alias androiddebugkey -storepass android -keypass android u got SHA1 value click this link u convert ur SHA1 value to HASH KEY im 100% sure this link will help u A: For Windows: * *open command prompt and paste below command keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%.android\debug.keystore | openssl sha1 -binary | openssl base64 *Enter password : android --> Hit Enter *Copy Generated Hash Key --> Login Facebook with your developer account *Go to your Facebook App --> Settings--> Paste Hash key in "key hashes" option -->save changes. *Now Test your android app with Facebook Log-in/Share etc. A: I was having the same exact problem, I wasnt being asked for a password, and it seems that I had the wrong path for the keystore file. In fact, if the keytool doesn't find the keystore you have set, it will create one and give you the wrong key since it isn't using the correct one. The general rule is that if you aren't being asked for a password then you have the wrong key being generated. A: You can use this apk 1.first install the app from the Google play store 2.install the above apk 3.launch the apk and input the package name of your app 4.then you will get the hash code you want A: https://developers.facebook.com/docs/android/getting-started/ 4.19.0 - January 25, 2017 Facebook SDK Modified Facebook SDK is now auto initialized when the application starts. In most cases a manual call to FacebookSDK.sdkInitialize() is no longer needed. See upgrade guide for more details. For Debug try { PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES); for (Signature signature : info.signatures) { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(signature.toByteArray()); Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT)); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } A: keytool -exportcert -alias androiddebugkey -keystore "C:\Users**Deepak**.android\debug.keystore" | "C:\Users\Deepak\ssl\bin\openssl" sha1 -binary | "C:\Users\Deepak\ssl\bin\openssl" base64 2 Changes in this above command 1.Deepak===Replace by your System USERNAME 2.C:\Users\Deepak\ssl=== replce your Open SSL path run this command and get output like this C:\Users\Deepak>keytool -exportcert -alias androiddebugkey -keystore "C:\Users\D eepak.android\debug.keystore" | "C:\Users\Deepak\ssl\bin\openssl" sha1 -binary | "C:\Users\Deepak\ssl\bin\openssl" base64 Enter keystore password: ****** ga0RGNY******************= A: I ran into the same problem and here's how I was able to fix it keytool -list -alias androiddebugkey -keystore <project_file\android\app\debug.keystore> A: private fun generateKeyHash(): String? {try { val info =packageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES) for (signature in info.signatures) { val md: MessageDigest = MessageDigest.getInstance("SHA") md.update(signature.toByteArray()) return String(Base64.encode(md.digest(), 0)) } } catch (e: Exception) { Log.e("exception", e.toString()) } return "key hash not found" } A: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Add code to print out the key hash try { PackageInfo info = getPackageManager().getPackageInfo( "com.facebook.samples.hellofacebook", PackageManager.GET_SIGNATURES); for (Signature signature : info.signatures) { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(signature.toByteArray()); Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT)); } } catch (NameNotFoundException e) { } catch (NoSuchAlgorithmException e) { } ... Save your changes and re-run the sample. Check your logcat output for a message similar to this: 12-20 10:47:37.747: D/KeyHash:(936): 478uEnKQV+fMQT8Dy4AKvHkYibo= Save the key hash in your developer profile. Re-run the samples and verify that you can log in successfully. A: please try this , it works for me : fun Context.generateSignKeyHash(): String { try { val info = packageManager.getPackageInfo( packageName, PackageManager.GET_SIGNATURES ) for (signature in info.signatures) { val md = MessageDigest.getInstance("SHA") md.update(signature.toByteArray()) return Base64.encodeToString(md.digest(), Base64.DEFAULT) } } catch (e: Exception) { Log.e("keyHash", e.message.toString()) } return "" }
{ "language": "en", "url": "https://stackoverflow.com/questions/7506392", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "241" }
Q: Using jackson to traverse json tree I'm developing a new system that talks to a third party via JSON. One of the calls returns a huge JSON structure to represent products and rules. I've used Jackson to convert this JSON into a tree quite easily. Now the issue is I want to be able to find nodes by 'querying' without manually traversing the whole tree. So somewhere deep in the tree is an object which has a field called business_id. I want to return all the nodes that have this field. Is that possible? A: You can use Jackson's JsonNode class documented here: http://fasterxml.github.io/jackson-databind/javadoc/2.5/com/fasterxml/jackson/databind/JsonNode.html Parse your data into a JsonNode (e.g. by ObjectMapper.readValue), then you can traverse programmatically that JSON structure as a tree. Look at methods like: as{datatype}, find[Value|Values], is[Array|Object|{datatype}], path etc. A: You could try Json Path, it lets you pick up a json node using it's xpath: http://code.google.com/p/json-path/
{ "language": "en", "url": "https://stackoverflow.com/questions/7506393", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: dynamically load rangy library As suggested here and exemplified here, rangy library can be used to highlight selected text. I do not have direct access to the page I want to highlight some text, so I'm trying to load it dynamically: var HLScripts=new Array( 'lib/log4javascript.js', 'src/js/core/core.js', 'src/js/core/dom.js', 'src/js/core/domrange.js', 'src/js/core/wrappedrange.js', 'src/js/core/wrappedselection.js', 'src/js/modules/rangy-serializer.js', 'src/js/modules/rangy-cssclassapplier.js', 'src/js/modules/rangy-selectionsaverestore.js', 'src/js/modules/rangy-highlighter.js' ) for(var i=0; i<HLScripts.length; i++) { var e=document.createElement('script'); e.type='text/javascript'; e.src='http://rangy.googlecode.com/svn/trunk/'+HLScripts[i]; document.body.appendChild(e); } However, when I call the init method rangy.init(); I obtain rangy is undefined. How can I correct this error? A: First, I'd recommend downloading a release build of Rangy and putting that on your server rather than linking directly to the files in the SVN trunk, which are not as stable as a proper release and are full of logging calls, which increase code size and harm performance and require log4javascript, which is itself fairly bulky. Second, loading scripts dynamically like that will load them asynchronously, meaning that an individual script may finish loading and execute before previous scripts upon which it depends have finished loading. Script loading and getting dependencies right is a bit of a tricky area. I'm no expert in this field, but for what it's worth, I'd recommend using a script loader such as LABjs to do it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506395", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How make a per-pixel output on WPF/XNA? I want to draw like in the old qbasik, where you can into 5 lines and PSET (x, y) derive any graph, or Lissajous figures. Question: what better way to go for WPF? and way for XNA? Any samples? A: For WPF and Silverlight WriteableBitmap http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.writeablebitmap.aspx WriteableBitmapEx library. Tries to compensate that with extensions methods that are easy to use like built in methods and offer GDI+ like functionality: http://writeablebitmapex.codeplex.com/ A: In XNA this isn't the most efficient thing in general, but I think your best bet is to probably create a texture and set each pixel using SetData, and render it to the screen with SpriteBatch. SpriteBatch spriteBatch; Texture2D t; Color[] blankScreen; protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); //initialize texture t = new Texture2D(GraphicsDevice, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, false, SurfaceFormat.Color); //clear screen initially blankScreen = new Color[GraphicsDevice.Viewport.Width * GraphicsDevice.Viewport.Height]; for (int i = 0; i < blankScreen.Length; i++) { blankScreen[i] = Color.Black; } ClearScreen(); } private void Set(int x, int y, Color c) { Color[] cArray = { c }; //unset texture from device GraphicsDevice.Textures[0] = null; t.SetData<Color>(0, new Rectangle(x, y, 1, 1), cArray, 0, 1); //reset GraphicsDevice.Textures[0] = t; } private void ClearScreen() { //unset texture from device GraphicsDevice.Textures[0] = null; t.SetData<Color>(blankScreen); //reset GraphicsDevice.Textures[0] = t; } protected override void Draw(GameTime gameTime) { spriteBatch.Begin(); spriteBatch.Draw(t, Vector2.Zero, Color.White); spriteBatch.End(); base.Draw(gameTime); } With this you can call either Set or ClearScreen at will in your Update or Draw. You may have to play with the texture index (I just used 0 for this example, might not be it for you), and also you only need to unset / reset one time per frame, so you can optimize that depending on how you use them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506398", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to generate all my entities composed two tables for each entity via a T4 automation I have a class library project for a data access layer that uses Entity Framework 4. My project needs a versioning concept. My database contains many tables that contain «Id» and «CreationDateTime». Each table is associated with a version table that contains the detail. All Tables are constructed in the same manner and suffixed with «Version» for the version table. I search for a way to generate all my entities (EF4 models) via a T4 automation that would unified Table and TableVersion (for the specified version) in one entity. This unified Entity must support get, insert, update and delete operations. Is it possible to do by modifying one of the T4 templates ? If it is, how ? Thanks a lot for any pointers. A: Probably not what you are looking for, but you can check out this blog post where I made similar proof of concept for journaling/versioning database. I have not used T4 (that is why I think this is probably not what you are looking for, but you may not find better solution) and generated entities, but inherited all entities from one base entity which had versioning properties. Basically, I extended DbContext by overriding SaveChanges method, and set my versioning properties there: foreach (var entry in this.ChangeTracker.Entries()) { // Make sure that this customized save changes executes only for entities that // inherit from our base entity (IEntity) var entity = (entry.Entity as JEntity); if (entity == null) continue; switch (entry.State) { // In case entity is added, we need to set OriginalId AFTER it was saved to // database, as Id is generated by database and cannot be known in advance. // That is why we save reference to this object into insertedList and update // original id after object was saved. case System.Data.EntityState.Added: entity.UserCreated = user; entity.DateCreated = now; insertedList.Add(entity); break; // Deleted entity should only be marked as deleted. case System.Data.EntityState.Deleted: if (!entity.IsActive(now)) { invalidList.Add(entity); continue; } entry.Reload(); entity.DateDeleted = now; entity.UserDeleted = user; break; case System.Data.EntityState.Detached: break; case System.Data.EntityState.Modified: if (!entity.IsActive(now)) { invalidList.Add(entity); continue; } entity.UserCreated = user; entity.DateCreated = now; JEntity newVersion = this.Set(entity.GetType()).Create(entity.GetType()) as JEntity; newVersion = this.Set(entity.GetType()).Add(newVersion) as JEntity; this.Entry(newVersion).CurrentValues.SetValues(entity); this.Entry(entity).Reload(); entity.DateDeleted = newVersion.DateCreated; entity.UserDeleted = user; break; case System.Data.EntityState.Unchanged: break; default: break; } } Link for full source code on github is in article. This solution uses same table for current and past versions of entity, and I'm planning to improve this concept by trying to put all "deleted" versions of entities into separate table, which would be private on DbContext, and all logic for transfer of items to history would be on save changes. That way would allow exposed public dbset to contain only current versions of item, allowing for any dynamic-data-like generic solutions to be built on top of such context. A: T4 templates can generate interface and attributes to "mark" your entities. After that, you can build generic classes to provide consistent policies or behaviors against your entities. Your question is very interesting. I will try to build an example for your case using the T4 templates in https://entityinterfacegenerator.codeplex.com
{ "language": "en", "url": "https://stackoverflow.com/questions/7506408", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: Aborting an HTTP request. Server-side advantage? In, for example, JavaScript AJAX libraries it is possible to abort an AJAX request. Is there any server side advantage to this or is it just for client-side cleanliness? Is it part of TCP? If, for example, I am requesting via AJAX a Python based server service – which is resource intensive – from my JavaScript Web App and abort this AJAX request, is it possible that aborting will ease the load on the server, or will the my ajax library just ignore the response from the server? A: It does not affect the server-side if you use your frameworks abort feature. The server will still process the request regardless. A: Once you made an HTTP request to a resource URL on your server (be it Asynch or not, aka ajax or "regular"), you can't abort it from your client / with another http request (unless your service has some weird listener that awaits for potential consequent http requests and stops itself up receiving one). My proposition, if you have one resource and time consuming operation, either split it into simpler operations, parallelize it or at east make some periodic responses to at least inform the user that it's still working and hasn't died
{ "language": "en", "url": "https://stackoverflow.com/questions/7506413", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: linkbutton click event I have dynamically added a linkbutton to the page. But the click event is not working. What could be the problem? Thanks for your help. I am adding a linkbutton on button click event. Here is my code. protected void Button1_Click(object sender, EventArgs e) { LinkButton lb = new LinkButton(); lb.Text = "dsadsa"; lb.ID = "22"; lb.CommandArgument = "22"; lb.CommandName = "22"; lb.Command += new CommandEventHandler(lb1_Command); PlaceHolder1.Controls.Add(lb); } protected void lb1_Command(object sender, CommandEventArgs e) { Label1.Text = e.CommandName; } A: the linkbutton isn't recreated when the linkbutton is clicked thus you're event handler isn't registered thus you're event doesn't get fired. Adding a button in an eventhandler is almost always a bad idea, you can add this by default on the page and just set it to Button.Visible = false. This way you can register your eventhandler earlier in say Page_Load and set it visible from the event handler. A: It's too late for adding the control on controls even handlers. The best way to add control is Init event, I guess on Load it will work too. A: You need to add the control in the page load as the link button is not created again after it is clicked. A: See both linkbutton click and linkbutton command in action: http://www.coderun.com/ide/?w=p-yDA-ntG0K4UrMkiImuRQ
{ "language": "en", "url": "https://stackoverflow.com/questions/7506414", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Millisecond timing C++ I want to time the real-time performance of some C++ functions I have written. How do I get the timing in milliseconds scale? I know how to get time in seconds via start=clock() diff=(clock()-start)/(double) CLOCKS_PER_SEC cout<<diff I am using Ubuntu-Linux OS and g++ compiler. A: Try diff = (clock() - start) * 1000.0 / CLOCKS_PER_SEC; The idea is that you multiply the number of clocks by 1000, so that whereas before you might get 2 (seconds), you now get 2000 (milliseconds). A: In Linux, take a look at clock_gettime(). It can essentially give you the time elapsed since an arbitrary point, in nanoseconds (which should be good enough for you). Note that it is specified by the POSIX standard, so you should be fine using it on Unix-derived systems. A: Notes: On my Dell desktop, which is reasonably quick ... ubuntu bogomips peak at 5210 time(0) takes about 80 nano-seconds (30 million calls in 2.4 seconds) time(0) allows me to measure clock_gettime() which takes about 1.3 u-seconds per call (2.2 million in 3 seconds) (I don't remember how many nano-seconds per time step) So typically, I use the following, with about 3 seconds of invocations. // //////////////////////////////////////////////////////////////////////////// void measuring_something_duration() ... uint64_t start_us = dtb::get_system_microsecond(); do_something_for_about_3_seconds() uint64_t test_duration_us = dtb::get_system_microsecond() - start_us; uint64_t test_duration_ms = test_duration_us / 1000; ... which use these functions // ///////////////////////////////////////////////////////////////////////////// uint64_t mynamespace::get_system_microsecond(void) { uint64_t total_ns = dtb::get_system_nanosecond(); // see below uint64_t ret_val = total_ns / NSPUS; // NanoSecondsPerMicroSeconds return(ret_val); } // ///////////////////////////////////////////////////////////////////////////// uint64_t mynamespace::get_system_nanosecond(void) { //struct timespec { __time_t tv_sec; long int tv_nsec; }; -- total 8 bytes struct timespec ts; // CLOCK_REALTIME - system wide real time clock int status = clock_gettime(CLOCK_REALTIME, &ts); dtb_assert(0 == status); // to 8 byte from 4 byte uint64_t uli_nsec = ts.tv_nsec; uint64_t uli_sec = ts.tv_sec; uint64_t total_ns = uli_nsec + (uli_sec * NSPS); // nano-seconds-per-second return(total_ns); } Remember to link -lrt
{ "language": "en", "url": "https://stackoverflow.com/questions/7506415", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to clear the *Backtrace* buffer in emacs How to delete all the error messages in the Backtrace buffer, so that when a new error occurs only the new error will be displayed instead of prepending with the old error. A: The backtrace buffer has its own mode with several command shortcuts. I use the 'q' key to kill the buffer and continue on but I'm sure others will work as well. Here's a list of them: http://www.cs.utah.edu/dept/old/texinfo/emacs18/emacs_26.html#SEC190
{ "language": "en", "url": "https://stackoverflow.com/questions/7506419", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Problem with MSVC Runtime Dependencies I have built several DLL's that use the MSVCRT.lib, which have all been successfully created however in Dependency Walker there are 5 missing dependencies, 1 of which is mine and is nothing to worry about. The other 4 dependencies are MSVCP90.dll MSVCR90.dll Delayed load of GPSVC.DLL Delayed load of IESHIMS.DLL I read that IESHIMS.DLL is nothing to worry about. How can I specify to my DLL to not include GPSVC.DLL if it is not needed. Is there a linker option for it. Note: I am doing this compile by command line from a maven script. A: GPSVC.DLL is the Group Policy client. It's delay loaded, so it will be loaded only when used. If you are not using Group Policy API, you can just ignore it. A: With windows the msvc runtimes are usually NOT stored in your application directory. Hence why dependency walker will show them as missing. There may be an option in depends to point to the directory where they are located, but I think that most likely not necassary.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506420", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Postgres window function column with Rails I'd like to use the rank() function PostgreSQL on one of my columns. Character.select("*, rank() OVER (ORDER BY points DESC)") But since I don't have a rank column in my table rails doesn't include it with the query. What would be the correct way to get the rank included in my ActiveRecord object? A: try this: Character.find_by_sql("SELECT *, rank() OVER (ORDER BY points DESC) FROM characters") it should return you Character objects with a rank attribute, as documented here. However, this may not be database-agnostic and tends to get messy if you pass around the objects. another (expensive) solution is to add a rank column to your table, and have a callback recalculate all records' rank using .order whenever a record is saved or destroyed. edit : another idea suitable for single-record queries can ben seen here
{ "language": "en", "url": "https://stackoverflow.com/questions/7506432", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Working with buttons in android Alright, so i've been making great progress on the app i'm trying to create, but most of the tutorials that i've been learning from only showcase the wondrous feature of having only one active widget inside the application at a time... The thing is, my application requires 2 or more buttons and that's the part i'm partially stuck at. My code implements a "SetWordsBtn" shown below (everything else is declared), public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); SetWordsBtn=(Button)findViewById(R.id.SetWordsBtn); SetWordsBtn.setOnClickListener(this); } which implements a onClick() like this: public void onClick(View view) { startWords(); } but what if i have another button that deletes the words such as "DelWordsBtn"? I was thinking i could declare both buttons simultaneously like this: SetWordsBtn=(Button)findViewById(R.id.SetWordsBtn); DelWordsBtn=(Button)findViewById(R.id.DelWordsBtn); SetWordsBtn.setOnClickListener(this); DelWordsBtn.setOnClickListener(this); but what about the onClick() method? Does it automatically apply itself to both the buttons when i do this? How am i able to declare a seperate onClick from each other so it both does different stuff when i click on either one of them? I was thinking the answer could be something like this, but i dunno : //Declarations SetWordsBtn=(Button)findViewById(R.id.SetWordsBtn); DelWordsBtn=(Button)findViewById(R.id.DelWordsBtn); SetWordsBtn.setOnClickListener(setWordsView); DelWordsBtn.setOnClickListener(delWordsView); //onClick Functions public void onClick(View setWordsView) { startWords(); } public void onClick(View delWordsView) { deleteWords(); } So it would actually link the startWords() function to the SetWordsBtn, and deleteWords() to DelWordsBtn... Any clear cut explanation/form of help would be appreciated. Thanks in advance guys. :) A: The typical convention is to just switch off of the ID of the View that is clicked. For example: View.OnClickListener listener = new View.OnClickListener() { @Override public void onClick(View v) { switch(v.getId()) { case R.id.SetWordsBtn: startWords(); break; case R.id.DelWordsBtn: deleteWords(); break; } } }; int[] ids = { R.id.SetWordsBtn, R.id.DelWordsBtn }; for(int i : ids) ((Button)findViewById(i)).setOnClickListener(listener); A: You can alternatively set up anonymous inner class(es) that listen, instead of having your Activity itself be the listener that implements OnClickListener. Example from the Android Button javadoc: button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Perform action on click } }); http://developer.android.com/reference/android/widget/Button.html P.S. start your local variable names, and method names, with lower case letters -- upper case is for class names. A: Where you suggested: public void onClick(View setWordsView) { startWords(); } public void onClick(View delWordsView) { deleteWords(); } If you think about it, there is no difference in the two method declarations and you would get a build error (method signatures are the same, even though the method parameter, View, has a different name). If I understand your question correctly then the answer given by kcoppock is correct. You also could define an Anonymous Class A: Drag and drop button on graghiclayout.xml ...>right click the button -->choose other properties....>choose inherited from view ---->click on click ....name it callme. That will be shows like this: xml file <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_x="76dp" android:layout_y="58dp" android:onClick="callme" android:text="Button" /> Run once your project: Open src --->activity .java ----->, do the coding like this: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); but=(Button)findViewById(R.id.button1); } public void callme(View v) { //Do somthing }
{ "language": "en", "url": "https://stackoverflow.com/questions/7506443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Catch a javascript error in an external script file I have a bit of JavaScript (Jquery Tools' Overlay) which may throw an exception when dropped on a page that uses it incorrectly, and I'm trying to handle it gracefully. I have a general window.onerror handler to rescue these errors and report them back to the server, however that's not getting triggered. I also cannot wrap a try/catch around this code, as it's being included as a remote script in HTML. Any ideas on how you can rescue errors that an external script throws? UPDATE: Here's the example. I should correct myself, window.onerror does get triggered, however the script does not continue running (in the example, the alert never alerts). <html> <script type="text/javascript"> window.onerror = function(e){ console.log("caught error: "+e); return true;} </script> <body> <!-- this is the line in the dom that causes the script to throw --> <a rel="nofollow"></a> <script type="text/javascript" src="http://www.google.com/jsapi"></script> <script type="text/javascript">google.load("jquery", "1.4.1");</script> <script src="http://cdn.jquerytools.org/1.2.5/tiny/jquery.tools.min.js"></script> <script type="text/javascript"> //this code will throw an error in jquery tools $("a[rel]").overlay(); alert("it's ok, I still ran."); </script> </body> </html> A: Here's a solution that should work in modern browsers. Older browsers may not catch syntax errors. <script> window.addEventListener('error', function(e) { alert(e.message); console.error(e.message, e.filename, e.lineno, e.colno, e.error); }); </script> <script> this is a syntax error in JavaScript </script> This works as well for external scripts <script src="foobar.js"></script>, but browsers will hide detailed error information by default for scripts hosted in different origins. You can fix it by using crossorigin, like this: <script crossorigin="anonymous" src="http://example.com/foobar.js"></script> More useful information: * *Is assigning a function to window.onerror preferable to window.addEventListener('error', callback)? *Sentry blog post about getting detailed error information from externally hosted scripts *Catching errors when a resource fails to load because of a 404 or a network error A: Define the error handler before any other script is loaded/executed. <script>window.onerror = function(e){alert(e);}</script> <script src="external.js"></script> <script> function ole(){alert("Hi!")} ole(); </script> When your script contains a syntax error, the error handler won't be called though (edit: in some older browsers): <script>window.onerror=function(e){alert(e);}</script> <script> !@ //The error won't be caught (at least not in older browsers) </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7506444", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: how to add share action to the post in facebook? i'm using this code to post to my application wall $attachment = array('message' => 'xxxxxxxxxxxxxxxx...', 'name' => 'xxxxxxxxxxxxxxxxxxx', 'caption' => 'xxxxxxxxxxxxxxxxxx', 'link' => 'xxxxxxxxxxxxxxxxxx', 'description' => 'xxxxxxxxxxxxxxxxxx', 'picture' => 'xxxxxxxxxxxxxxxxxx', 'actions' => array(array('name' => 'Download!', 'link' => 'xxxxxxxxxxxxxxxxxx')) ); $result = $facebook->api('/2222222222222/feed/','post',$attachment); when i post to my application wall manually the post is appearing on the application users wall with the share action but when i use the above code it only appear on the app wall with like and comment actions only. why? and how to add the share action to the actions array? A: i didn't find any answer online, but i just found the solution to my problem by chance i removed the action parameter from the attachment. but if there is a link parameter in the attachment the share action won't appear so you will have to give up the link parameter. A: the proper names for the action link is: array( array('text' => 'Download!', 'href' => 'xxxxxxxxxxxxxxx')); Keep in mind that you can't use action links in the graph api (yet). so this functionality is limited to the REST api. Let me know if this helps A: http://facebookanswers.co.uk/?p=270 This article explains it. The key is this: 'actions' => array('name'=>'Sweet FA','link'=>'http://www.facebookanswers.co.uk'), This is fine for adding one action. However, I'm not sure how to add two. A: Hi the solution is here instead of $result = $facebook->api('/2222222222222/feed/','post',$attachment); use $result = $facebook->api('/2222222222222/links/','post',$attachment); i'm still facing one little problem with the picture not showing after this change, if i come to a solution to it I'll come back here and post it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506457", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Implementing Scheduler in free RTos I need some help. I have a project to build an alternative scheduler for freeRTos, with a different algorithm, and try to replace it in the OS. My questions are: * *Is it possible in normal time? (for about few months) *How do I recognize the code of the scheduler in the whole OS code? A: Given that FreeRTOS is only a few thousands lines of code it is certainly possible within a few months. If you know how to write a scheduler, of course. However, FreeRTOS doesn't even have a real scheduler. It maintains a list of runnable tasks, and at every scheduling point (return from interrupt or explicit yield), it takes the highest priority task from that list. A: To add more answers to question 2: Task controls are in tasks.c, portable/port.c contains context switches. Have a look at the source organization doc; a given function name gives away which file it's defined it. There really isn't too many places where they can be either. Use grep :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7506461", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Playing multiple Silverlight MediaElements at once Here is the problem: I have a Silverlight application where we would like to play 8 Silverlight MediaElements at once. All are playing .MP4 videos. The first 6 will load almost immediately, and have the MediaOpened within a second or two. The remaining 2 will sometimes (not always) take minutes before playing / reporting that they are ready to play. If I just play 6 or less, there seems to be no problem. Here is what I've found: 1) There is no relation to the files. I can switch the order of the MediaElements and the first 6 I attempt to open will open just fine and the remaining will block. 2) There isn't necessarily a bandwidth issue (I tried compressing the files down to almost nothing and the same thing happened). 3) This isn't an IIS issue (my server), I don't think, since I've maxed out simultaneous connections. 4) My client machines are not pegged at all. The network is consistent at 25%, so it's possible the remaining 2 are being starved out there, but what's magic about the 7th and 8th? Code My code seems unimportant, but I will include it because people seem to like it when you do: foreach ( String Uri in UriList ) { //For every URI we create a new MediaElement. In our test case this is 8 always. MediaElement newMediaElement = new MediaElement(); // We use MediaOpened as our 'ready to play' event. Buffering remains at 0 for the // two streams that don't work. newMediaElement.MediaOpeened += new System.Windows.RoutedEventHandler(stream_MediaOpened); //Set the source and add it to some list to be added to a grid later... newMediaElement.Source = uri; MediaElementList.Add( newMediaElement ); } Following this the MediaElementList gets added to a Grid defined in XAML. If people think more code will be helpful I'll add the specific parts. Like I said, I don't think the code will be useful, but you never know... Other research Other people have this problem, but we haven't found a solution. We've seen this and this and this, but none of them give any answer other than they don't know. EDIT: Okay, so there's a limit of 6, as Kevev points out. Does anyone know of any way around this? A: The Silverlight 4 HTTP networking stack is limited to 6 concurrent connections. See here under the Client HTTP Processing section: Concurrent connection limit is raised from 2 to 6
{ "language": "en", "url": "https://stackoverflow.com/questions/7506464", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C naming convention Possible Duplicate: What are the most common naming conventions in C? Is there a official (or widely used) naming convention for the C language after all? One like Java's naming convention (UpperCamelCase case for classes, lowerCamelCase for methods, etc)? I've seen many different conventions, like variable_name, variableName, variablename, etc. Is there one that is used by most C programmers? EDIT: Just to make it clearer, the question is if there is or there is not mostly used naming convention. Like one that programmers don't have to think about (like Java's, or C#'s). A: In the style of the C standard: Variable, function and struct naming schemes are undefined. Use whatever style you prefer for your own new projects, keep consistent style within other codebases. Personally I use camelCase - less use of shift and no annoying type encoding into variables, any decent IDE should be able to tell me what type a variable is. A: Depends, e.g. if you write code in the linux kernel use snake_case. See coding guidelines for the kernel. A: If you're working on existing code, follow the existing naming convention used in that code. The only thing worse than a bad naming convention is a mixture of inconsistent naming conventions. (The same applies to brace styles, indentation level, and so forth.) If you're writing new code, I'd personally recommend looking at the sample code in K&R and the C standard, but it's up to you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506470", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MYSQL REPORTING is there a more efficent way to get rows fro ma table from the current week, last week, current month and current year to this // current month SELECT * FROM crm_tasks WHERE YEAR( date_completed ) = YEAR( CURDATE( ) ) AND MONTH( date_completed ) = MONTH( CURDATE( ) ) // current week SELECT * FROM crm_tasks WHERE YEAR( date_completed ) = YEAR( CURDATE( ) ) AND WEEK( date_completed ) = WEEK( CURDATE( ) ) // last week SELECT * FROM crm_tasks WHERE YEAR( date_completed ) = YEAR( CURDATE( ) ) AND WEEK( date_completed ) = WEEK( CURDATE( ) ) - 1 // current year SELECT * FROM crm_tasks WHERE YEAR( date_completed ) = YEAR( CURDATE( ) ) A: You should be able to use a query similar to this SELECT * FROM crm_tasks WHERE date_completed >= @FirstDayOfYear AND date_completed < @FirstDayOfNextYear Where @FirstDayOfYear and @FirstDayOfNextYear are filled in appropriately. If you have an index on date_created, this should work reasonably fast. This can be altered for any period you want to use.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506471", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Registry in inno setup I am new to creating installers. Before used the Microsoft visual studio deployment package. Now trying inno setup, pretty awesome. I saw that Visual studio one wrote some registries when installed. Do I have to create Registries for my package too? I have a visual c# application and need to create a installer for my company. Main intention is to create a installer that will easily update the old one, but this is a first version of software we are going to release to customers. Much appreciated. I saw tutorials of Registry in internet, but the point of creating is the one that I don't understand. A: I'm not sure what you are asking exactly. If you mean how do I write to the Windows Registry, you create a [Registry] section in your inno-setup file and add what you need. Here is a link to the documentation. A: You don't HAVE to write any registry entries unless your app requires them. Inno automatically creates the usual entries to allow uninstall from the Add/Remove programs applet. Inno will also automatically handle upgrades with no special effort. If you have previously distributed the app using an MSI package, then you will either need to allow side by side installs (different folders, etc) or uninstall the previous version first. The article above has a sample of how to get the uninstall path.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506475", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Scala: Passing instance of child class to parent class function Why does the Scala repl say: <console>:10: error: type mismatch; found : Car#Door required: _1.Door where val _1: Car When I run this statement: var c = New Car c.is_door_open(c.door) That refers to this class: class Car { var door = new Door(true) class Door (var state: Boolean = true) { } def is_door_open(d: Door) { println(d.state) } } A: When you have an inner class as Door here, each instance of class Car defines a different Door type. In is_door_open(d: Door), Door means a Door of the enclosing instance of Car. The type Car#Door in the error message means a Door of any Car, it is the common type to all doors. When you call c.is_door_open(c.door) the Car of c.door must be the same as the the c of c.is_door_open, as that is what the declaration of is_door_open requires (it should have been d: Car#Door otherwise). And moreover, they must be the same to the satisfaction of the compiler, which has some precise rules for that. Here it seems obvious the cars are the same. Not so, because c is a var, so not a stable identifier. Imagine the code c.is_door_open({c = new Car; c.door}). Contrived of course, but this shows that you cannot rely on both occurence of c being the same car. So among your solutions, depending of what your real code may be : * *Make c a val instead of a var *declare is_door_open parameter as d: Car#Door *Stop making Door dependant on instance of Car, declare it outside the class, if you want it to be Car.Door, put it in a companion object Car rather than in class Car *Make is_door_open a method of Door (without a Door argument then) rather than Car. It has full access to the enclosing Car (with Car.this as in java, or declaring an alias for this in Car with class Car {car => )
{ "language": "en", "url": "https://stackoverflow.com/questions/7506478", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Problems with control of primefaces components by Managed Bean I hope somebody could help me with the trouble I am having with JSF 2 and Primefaces 3.0M3. the problem is that the back bean methods do not fired from any component in the layoutunit 'center' they are inside a form and nothing happens, even I tried to update the components with remoteCommand, autoUpdate of the outputpanel, commandButton with action and actionListener and nothing, there is no error message. In the layoutunit west works the components well, renders the outputpanel (pfpInfo) of the center layoutunit but I do not know what is happening. here is the code <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:p="http://primefaces.prime.com.tr/ui" xmlns:c="http://java.sun.com/jsp/jstl/core"> <h:head> <title>Articulos</title> </h:head> <h:body> <link rel="stylesheet" type="text/css" href="../css/estilos.css" /> <p:layout fullPage="true" id="lay"> <p:layoutUnit position="north" size="100" resizable="false" closable="false" collapsible="false"> <img src="../images/logo.jpg" alt="PLL" style="width: 413px; height: 83px;" align="left"></img>ss <img src="../images/tel.jpg" alt="PLR" style="width: 413px; height: 83px;" align="right"></img> </p:layoutUnit> <p:layoutUnit position="west" size="200" header="Categorías" resizable="false" closable="false" collapsible="false"> <h:form id="frWest"> <p:growl id="message" showDetail="true" globalOnly="true" autoUpdate="true"></p:growl> <p:tree id="treeSingle" value="#{controlMBean.raizArbol}" var="rama" dynamic="true" selectionMode="single" selection="#{controlMBean.ramaElegida}" expanded="true"> <p:ajax event="select" update=":frCenter:pfSeg :frCenter:pfpInfo :frCenter:pfpIma" listener="#{controlMBean.procesaInformacionArt}"></p:ajax> <p:treeNode> <h:outputText value="#{rama}" styleClass="encabezadoUiLight" /> </p:treeNode> </p:tree> </h:form> </p:layoutUnit> <p:layoutUnit position="center"> <h:form id="frCenter"> <p:outputPanel id="pfSeg" rendered="true"> <p:outputPanel id="pfpIma" rendered="#{not controlMBean.cargado}"> <img src="../images/luchadores.jpg" /> </p:outputPanel> <p:outputPanel id="pfpInfo" rendered="#{controlMBean.cargado}" autoUpdate="true"> <p:dataTable dynamic="true" var="prnda" rowKey="#{prnda.id}" value="#{controlMBean.infoArts}" paginator="true" rows="10" selectionMode="single" paginatorAlwaysVisible="false" selection="#{controlMBean.artElegido}" rendered="#{controlMBean.cargado}"> <p:ajax event="rowUnselect" listener="#{prestalana.deseleccionar}"></p:ajax> <f:facet name="header">Articulo(s)</f:facet> <p:ajax update=":frCenter:ppImg :frCenter:pgInfo" oncomplete="prnd.show()" event="rowSelect" listener="#{controlMBean.elegirFila}"></p:ajax> <p:column sortBy="#{prnda.id}"> <f:facet name="header"> <h:outputText value="Id" /> </f:facet> <h:outputText value="#{prnda.id}" /> </p:column> <p:column sortBy="#{prnda.articulo}"> <f:facet name="header"> <h:outputText value="Modelo" /> </f:facet> <h:outputText value="#{prnda.articulo}" /> </p:column> <p:column sortBy="#{prnda.marca}"> <f:facet name="header"> <h:outputText value="Marca" /> </f:facet> <h:outputText value="#{prnda.marca}" /> </p:column> <p:column sortBy="#{prnda.edo}"> <f:facet name="header"> <h:outputText value="Ubicación" /> </f:facet> <h:outputText value="#{prnda.edo}" /> </p:column> <p:column sortBy="#{prnda.stsArticulo}"> <f:facet name="header"> <h:outputText value="Estatus" /> </f:facet> <h:outputText value="#{prnda.stsArticulo} " /> </p:column> <p:column sortBy="#{prnda.precio}"> <f:facet name="header"> <h:outputText value="Precio" /> </f:facet> <h:outputText value="$ #{prnda.precio}" /> </p:column> </p:dataTable> <p:commandButton action="#{controlMBean.probar2}" actionListener="#{controlMBean.probar}" value="Prueba"></p:commandButton> </p:outputPanel> <br /> <h:outputText value="#{controlMBean.mensaje}" styleClass="textoUiLight" id="hotMen" /> </p:outputPanel> <p:remoteCommand actionListener="#{controlMBean.probar}" name="pruebaRc" update=":frCenter:ppImg"></p:remoteCommand> <p:dialog appendToBody="true" dynamic="true" header="Info Prenda" onShow="pruebaRc" widgetVar="prnd" resizable="false" width="750" height="550" showEffect="fold" position="center" hideEffect="explode"> <p:outputPanel id="ppImg" autoUpdate="true"> <h:panelGrid columns="2" id="pgInfo"> <p:galleria transitionInterval="3000" var="i" value="#{controlMBean.imagenes}" panelWidth="#{controlMBean.width}" panelHeight="#{controlMBean.height}" frameHeight="#{controlMBean.height/4}" frameWidth="#{controlMBean.width/4}" effect="flash"> <p:graphicImage id="img" height="#{i.alto}" width="#{i.ancho}" value="#{controlMBean.ruta}#{i.nombre}.jpg" /> </p:galleria> <h:panelGrid columns="2" width="350"> <h:outputLabel value="ID:" styleClass="etiqueta" /> <h:outputText value="#{controlMBean.artElegido.id}" styleClass="resultado" /> <h:outputLabel value="Prenda:" styleClass="etiqueta" /> <h:outputText value="#{controlMBean.artElegido.prenda} adasd" styleClass="resultado" /> <h:outputLabel value="Precio:" styleClass="etiqueta" /> <h:outputText value="$#{controlMBean.artElegido.precio}" styleClass="resultado" /> <h:outputLabel value="Marca:" styleClass="etiqueta" /> <h:outputText value="#{controlMBean.artElegido.marca}" styleClass="resultado" /> <h:outputLabel value="Sucursal:" styleClass="etiqueta" /> <h:outputText value="#{controlMBean.artElegido.suc}" styleClass="resultado" /> <h:outputLabel value="Descripcion:" styleClass="etiqueta" /> <h:outputText value="#{controlMBean.artElegido.descr}" styleClass="resultado" style="width:300px;height:100px;" /> </h:panelGrid> </h:panelGrid> </p:outputPanel> </p:dialog> </h:form> </p:layoutUnit> </p:layout> </h:body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/7506479", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is causing huge performance differences in these c write() calls? Does anybody see the difference between these two lines? 1) ret = write( fd_out, local_bugger, bytes_to_move); 2) nwritten = write (fd, buf + total_written, size - total_written); Obviously, not the naming conventions. Specifically, one is writing over the network 4x faster than the other. Looking for logic , flags, etc THANKS A: what are the values/types of all those? Right now this question can't be answered... does option 2) end up writing 4x as much data? What are the flag options on the fopens for the two handle? etc... Right now I'll guess that it's because mars is ascendent in jupiter and the moon is gibbous waxing, causing the higgs bosons to mess with the quarks in your ethernet cable. A: There could be two things at play here: * *The size of the chunks you're writing. Small chunks incur more overhead. But that's unlikely to cause a big difference unless you're writing less than 16 bytes or so. *The details of the file descriptor you're writing to. How much buffering does it have? Is it going through a filesystem (NFS or CIFS)? Is it even going out over the same network? In short, as Marc B answered: not enough information.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506482", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Compiling C++ with cygwin doesn't search provided include paths I am working within a tree that compiles fine on any Unix machine I throw it at, but Cygwin is being difficult and I'm not really sure where to start. I have the following directory structure: buildwin/ |-- main.cpp |-- other project files |-- include/ |-- tclap |-- CmdLine.h |-- other files (including CmdLine.cpp) |-- eigen |-- (appropriate files) |-- rapidxml |-- (appropriate files) When I try to compile this, I get the following error from g++: $ g++ main.cpp -lglut32 -lglu32 -lopengl32 -Iinclude/eigen -Iinclude/rapidxml -Iinclude/tclap main.cpp:6:27: fatal error: tclap/CmdLine.h: No such file or directory compilation terminated. I know it's finding the other libraries (eigen and rapidxml) fine because if I remove the respective include flags, it throws an error saying that it can't find eigen or what have you. The include statement in question is: // snip #include <Eigen/StdVector> #include <cmath> #include <iostream> #include <fstream> #include <tclap/CmdLine.h> // snip Ideas? Thanks! A: You're specifying -Iinclude/tclap, then include tclap/CmdLine.h, so the compiler goes hunting for include/tclap/tclap/CmdLine.h. Either use -Iinclude, or include CmdLine.h without the path. A: Does using -Iinclude work? You probably don't need to be explicitly adding the subdirs of include because you refer to them in the names in the #include statements.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506485", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: textbox autosuggest in asp vb The application is written in ASP VB classic and various Java scripts. I am faced with some issues 1) When I select an entry in a dropdown box, I can use the "onBlur" method to do what is needed at that point What is the method available for an AutoSuggest Textbox that I can employ once a) The desired entry is selected from the list (such as "onSelect"). b) The user never selects, but actually types the entire selection manually. In that case, I would need a method such as "onBeingDoneTyping" 2) When a regular dropdown is defined, I can display a user friendly description (like first and last name). In the meantime, internally I can retrieve what the index of that record is with the first entry of the parameter "value", in my case: PatientID. " " " <%=lsSelected%> ><%=PatientName%> How can that be accomplished when using the AutoSuggest feature in a textBox? Say I allow "First-Name Last-Name" Is there a hidden parameter that can be used that would let me know the index of the selected entry? In addition, should I create a column in the data base "FirstLastName" to speed up the search? A: For (1) you're after an auto-complete function. I've used this jQuery with classic-ASP a few times (excellent little plugin): http://docs.jquery.com/Plugins/Autocomplete - there's a good demo and example source there. For (2) - assuming that you're using the jQuery plugin, then your object is a textbox, not a select object. So if the textbox you created is: <input type="text" name="example" id="example" /> when the form is submitted any request.form("example") will return the text entered, not the index/selected value from any list of options.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506488", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MonoDevelop Insert Mode always on? I've updated to the latest versions of MonoTouch and MonoDevelop. I can't seem to highlight ensure rows of text at a time by using the shift key + up/down arrows. I've also noticed that "--INSERT--" appears in the bottom left status bar. The cursor is also a box instead of the usually single line. I'm using a mac book pro, so there is no insert key, and pressing fn + return doesn't seem to have any effect. How do I turn insert mode on and off? I've also noticed that it sometimes says "--VISUAL--", but I can't find any links when I google these tiems. A: You've enabled vi mode. Turn it off in MD preferences.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Oracle WITH clause returns no data I am trying to use a WITH clause in Oracle, but it is not returning any data. This is the query I am trying to run... with test as (select count(*) from my_table) select * from test; When I run this code, I get back the count of the records in my_table select count(*) from my_table I am on Oracle 10g so the query should work... select * from v$version; yields Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bi PL/SQL Release 10.2.0.4.0 - Production CORE 10.2.0.4.0 Production TNS for Solaris: Version 10.2.0.4.0 - Production NLSRTL Version 10.2.0.4.0 - Production Could it a permissions issue or something? *EDIT: * I believe my question is clear. Using the WITH statement will not return any records for me, even though the "select count(*) from my_table" statement inside the WITH statement works correctly, which would lead me to believe that there is another issue that I am unable to figure out, hence this question :) EDIT 2 OK, so if I try and execute the query from a linked server from SQL server management studio I get some error information back: sg 7357, Level 16, State 2, Line 1 Cannot process the object "with test as (select count(*) from v$version) select * from test;". The OLE DB provider "MSDAORA" for linked server "MyServer" indicates that either the object has no columns or the current user does not have permissions on that object. A: Try giving the aggregate an alias name. with test as (select count(*) as MyCount from my_table) select MyCount from test; A: The following worked just fine for me (10gR2) SQL> with test as 2 (select count(*) 3 from user_tables) 4 select * 5 from test; COUNT(*) ---------- 593 SQL> What client are you using? A: Maybe the optimizer is materializing the count query (dumb, I agree). It's a shot in the dark but do you have these privileges? * *grant query rewrite to youruser; *grant create materialized view to youruser; A: This question is confusing. Are you saying you are or are not getting back the count from my_table? You should be getting back the count because that's exactly what you asked for in the with clause. It's analogous to writing: select * from (select count(*) from my_table); A: Some people at my company ran into this the other day - we traced it down to the Oracle client version [and thus the OCI.dll] version that was being picked up by PL/SQL developer. Some of our dev PCs had Oracle 8 (!) client installs still knocking around on them as well as more recent versions. The symptom was that not only were queries written using a WITH clause returning no rows, they were returning no columns either! If you manually set the app to pick up the Oracle 11 oci.dll then it all worked. I think what is going on is that Oracle 8 predates the WITH clause (introduced in Oracle 9, and enhanced subsequently). Now, mostly you can get different versions of the Oracle client and server to talk to one another. However because the client has a certain amount of 'intelligence', it is supposed to be semi-aware of what sort of operation it is submitting to the database, and so does some form of primitive parse of the SQL. As it doesn't recognize the command as a SELECT, it treats it as some unknown command [e.g. possibly a DDL command] and doesn't recognize it as returning a resultset. If you turn on SQL_TRACE for the session you can see the SQL gets PARSEd and EXECUTEd fine on the server, but that no calls to FETCH are made. I had a similar thing myself recently when trying to use the new WITH syntax in Oracle 12 that allows an inline function definition. If you try simple examples using an Oracle 11 thick client-based application, such as PL/SQL developer or SQL*Plus, then you get an error. If you use an Oracle 12 client, or a thin-client application that doesn't rely a client-side install, then it works.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506499", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using Ruby and SQL SMO for Script Automation I need to create a script in ruby to get all the database objects (tables,views,sps, functions, etc) and be able to create files for each of the db objects. I would like to be able to implement this solution in ruby and use some sort of Win32 class may be?. I am using SQL Server 2008 R2. Not ruby on rails of course. A: # == Name # SQL Server Library # == Author # Maverick # == Synopsis # ADO SQL Server Library # == Notes: # Modify the following global variables in order to set up an execution environment # sql_str: This is the SQL CMD command option and arguments -> Change the -U and -P arguments for -E to enable integrated security # http://rubyonwindows.blogspot.com/2007/03/ruby-ado-and-sqlserver.html Thread.abort_on_exception = true require 'win32ole' require 'win32api' CoInitialize = Win32API.new('ole32', 'CoInitialize', 'P', 'L') # This class manages database connection and queries class SqlServer attr_accessor :connection, :data, :fields def initialize @connection = nil @data = nil @cmd_time_out = 900 end #opens a database connection using integrated security def open(server,database) connection_string = "Provider=SQLOLEDB.1;" connection_string << "Persist Security Info=False;" connection_string << "Integrated Security=SSPI;" connection_string << "Initial Catalog=#{database};" connection_string << "Data Source=#{server};" connection_string << "Network Library=dbmssocn" CoInitialize.call( 0 ) if server.eql?(nil) or database.eql?(nil) or server.eql?('') or database.eql?('') then raise Exception, "Application Error: Server or Database parameters are missing" end begin @connection = WIN32OLE.new('ADODB.Connection') @connection.ConnectionString = connection_string @connection.open rescue Exception => e @connection.Errors.Count.times { |x| show_ado_error(@connection.Errors) } raise Exception, "Application Error: #{e.message} \n Can't open a connection with the server. Verify user credentials" end end def get_connection return @connection end #executes a query without returning any rows def execute_non_query(query) begin command = WIN32OLE.new('ADODB.Command') command.CommandType = 1 command.ActiveConnection = @connection command.CommandText = query command.CommandTimeOut = @cmd_time_out result = command.Execute if @connection.Errors.Count > 1 then raise Exception,"ADODB Connection contains errors" end rescue Exception => e show_ado_error(@connection.Errors) raise Exception, "Application Error: #{e.message} \n Can't execute query. Verify sql syntax" end return result end #prints ado db errors using ado connection error property def show_ado_error(obj) obj.Count.times { |x| puts "#{x}. ADODB Error Number: " + @connection.Errors(x).Number.to_s puts "#{x}. ADODB Generated By: " + @connection.Errors(x).Source puts "#{x}. ADODB SQL State: " + @connection.Errors(x).SQLState puts "#{x}. ADODB Native Error: " + @connection.Errors(x).NativeError.to_s puts "#{x}. ADODB Description: " + @connection.Errors(x).Description } end #executes a query returning an array of rows def execute_query(sql_query) # Create an instance of an ADO Record set begin record_set = WIN32OLE.new('ADODB.Recordset') # Open the record set, using an SQL statement and the # existing ADO connection record_set.open(sql_query, @connection) # Create and populate an array of field names @fields = [] record_set.fields.each do |field| @fields << field.Name end begin # Move to the first record/row, if any exist record_set.movefirst # Grab all records @data = record_set.getrows rescue @data = [] end record_set.close # An ADO Recordset's GetRows method returns an array # of columns, so we'll use the transpose method to # convert it to an array of rows @data = @data.transpose rescue raise Exception, "Application Error: Can't execute query. Verify SQL Query syntax" end end def close @connection.Close end end
{ "language": "en", "url": "https://stackoverflow.com/questions/7506501", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Mapping an entity to 2 tables I have a position class that i want to be able to write to the database. I currently have a entity for the class that is mapped to the database. I want to because to have the class insert data into one table and update entries in the other table. One table is for current positions and the other is for historical positions. Is it possible to map an entity to 2 tables and have it update 1 table and insert into the other? A: Just don't do this. Use a database insert trigger. A: Wouldn't it be easier to have a Trigger on the Update that Insert automatically a copy of the data in your history table? A: I would make 2 different entities for this. If you want this to map to a single entity in your application you should write a data access class that (based on the data of your single entity) determines whether to do an update or an insert. And I would personally never ever use a trigger for such a thing as this is business logic to me that needs to be exposed in the application so it can be tested.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506504", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: is there a way to identify the last control that was active in a .net windows forms code-behind? I have a form where there is group of radio controls and some with textbox. If the cursor is on textbox and i try switching the cursor to a different radio button, i should be able to identify the last active control( in this case.. the textbox) and do some validation. The LostFocus() event of textbox pops up message indicating that "this item should be filled in..". But if i want to go with a different radiobutton option in the same group, i dont want this message popping unnecessarily. How do i avoid that? A: The TextBox has Validating and Validated events-- you should use those instead of the LostFocus event. In the case of Validating, you can stop the user from leaving the TextBox if the criteria isn't correct. If you must use "something" like LostFocus, use the Leave event instead. There is no "Last Active Control" type function. You would have to track that yourself by setting a variable on the Enter event of those controls. That will lead to an ugly mess to maintain in my opinion. Validate at the form level is probably the best choice for the end user.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506506", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dynamically change a specific color Possible Duplicate: How can I generate multiple shades from a given base color? How can change a color and make it more dark or brighter? I am using Delphi 2007. A: You can use a unit like this one: http://www.delphipraxis.net/157099-fast-integer-rgb-hsl.html HSL stands for: * *Hue *Saturation *Luminance So, if you change the luminance... you can get a darker or brighter color...
{ "language": "en", "url": "https://stackoverflow.com/questions/7506513", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: User-entered apostrophe crashes android app (SQL-related) My application currently utilizes a SQLite database to store messages for the user. If a user enters an apostrophe in any of the fields, however, the database crashes. I realize that the issue is due to SQLite using the apostrophe as a quote delimiter (I place single apostrophes around the message text stored), but can't think of any good ways around this. Is there a common practice to storing strings with apostrophes in an SQLite database? Here's an example of an error I received: java.lang.RuntimeException: Unable to resume activity {x.x.x.x/x.x.x.x.Main}: android.database.sqlite.SQLiteException: near "m": syntax error: , while compiling: SELECT title, contact_name, contact_number FROM contacts WHERE title='I'm at work' at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3128) at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3143) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2684) at android.app.ActivityThread.access$2300(ActivityThread.java:125) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:123) at android.app.ActivityThread.main(ActivityThread.java:4627) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:521) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:859) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:617) at dalvik.system.NativeStart.main(Native Method) Caused by: android.database.sqlite.SQLiteException: near "m": syntax error: , while compiling: SELECT title, contact_name, contact_number FROM contacts WHERE title='I'm at work' at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method) at android.database.sqlite.SQLiteCompiledSql.compile(SQLiteCompiledSql.java:91) at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:64) at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:80) at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:46) at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:42) at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1454) at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1338) at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1293) at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1373) ... 19 more A: General database guidelines (and secure coding guidelines) help prvent against this because the same thing that's causing your error can be exploited for SQL INjection attacks. The most common defenses are (in order of preference per OWASP guidelines): * *Use parmeterized stored procedures *Use parameterized queries if the DB Engine supports it. *As a final resort, escape the strings (implementation dependednt on the database engine.) SQLLite supports options 2 and 3. From this page: http://www.sqlite.org/lang_expr.html A string constant is formed by enclosing the string in single quotes ('). A single quote within the string can be encoded by putting two single quotes in a row - as in Pascal. C-style escapes using the backslash character are not supported because they are not standard SQL. so O'Brien would be entered as O''Brien in your SQL statement. And per this page, you can use parameterized queries: http://www.sqlite.org/limits.html INSERT INTO tab1 VALUES(?,?,?); Then use the sqlite3_bind_XXXX() functions to bind your large string values to the SQL statement. The use of binding obviates the need to escape quote characters in the string, reducing the risk of SQL injection attacks. It is also runs faster since the large string does not need to be parsed or copied as much. A: See this question - there are quite a few answers which should help you. Specifically it talks about using DatabaseUtils.sqlEscapeString or: uservalue = getText().tostring(); uservalue = uservalue.replace("'","\'"); //execute query... A: the one line simplest code : String s = editText.getText().toString().replace("'","\'"); A: Just use android standard API as userInput = android.database.DatabaseUtils.sqlEscapeString(userInput); It will solve your problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506519", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Can't apply .addClass to dynamically created element I'm trying to apply .addClass to the the last item in an unordered list. The problem is, the unordered list is dynamically created from an external script. So I guess you can say, the script isn't really there until the external script constructs it. The script seems to load this in after the page and DOM is ready. I've tried the old basics, but to no avail: $(function() { $("#svpply_items li:last-child").addClass('last'); }); $(document).ready(function() { $("#svpply_items li:last-child").addClass('last'); }); Any help would be hugely appreciated. A: I would say make sure that all the scripts are at the bottom of you page and make sure that the ordering of external scripts is correct. If that's already the case or you've already tried that to no avail, then take a look at the $.getScript(...) function. Something like this: $(document).ready(function () { $.getScript('scripts/external.js', function (data, textStatus) { $("#svpply_items li:last-child").addClass('last'); }); }); A: Why not try it on $(window).load(function(){.... ? A: Try this: $("#svpply_items").bind("DOMSubtreeModified", function() { $(this).find('li:last-child').addClass('last'); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7506521", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: preg_replace for a specific URL containing parameters I'm trying to replace the session ID # of a list of URLS Ex: http://www.yes.com/index.php?session=e4bce57bc39f67bebde0284f4c2ed9ba&id=1234 I'm trying to get rid of the session=e4bce57bc39f67bebde0284f4c2ed9ba bit and just keep the http://www.yes.com/index.php?id=1234 bit. I'm attempting to use: preg_replace('&\bhttp://www\.yes\.com/(?:index\.php(?:\?id(?:=[]\d!"#$%\'()*+,./:;<=>?@[\\\\_`a-z{|}~^-]*+)?&i', $subject, $regs)) But it isn't work. Any help would be appreciated. Thanks! A: If you just want to strip out the &session=... part then preg_replace might be the best option. It also makes sense to look just for that part then and not to assert the URL structure: $url = preg_replace("/([?&])session=\w+(&|$)/", "$1", $url); This pattern looks that it's either enclosed by two &, and/or begins with an ? and/or is the last thing in the string. \w+ is sufficient to match the session id string. A: Slightly more verbose than a regex, but you can do this using PHP's own functions for url handling, parse_url, parse_str, http_build_url and http_build_query. // Parse the url to constituent parts $url_parts = parse_url($_REQUEST); // Parse query string to $params array parse_str($url_parts['query'], $params); // Get rid of the session param unset($params['session']); // Rebuild query part of the url without the session val $url_parts['query'] = http_build_query($params); // Rebuild the url using http_build_url $cleaned_url = http_build_url( "http://www.example.com" , $url_parts );
{ "language": "en", "url": "https://stackoverflow.com/questions/7506522", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Can I declare a class within a function in Python? How can I define class Options inside of my CheckForJiraIssueRecord function? def CheckForJiraIssueRecord(object): #sys.stdout = open(os.devnull) #sys.stderr = open(os.devnull) class Options: pass options = Options() options.user = 'user' options.password = 'password' try: com = jira.Commands() logger = jira.setupLogging() jira_env = {'home':os.environ['HOME']} command_cat= "cat" server = "http://jira.server.com:8080/rpc/soap/jirasoapservice-v2?wsdl" except Exception, e: sys.exit('config error') try: jira.soap = jira.Client(server) jira.start_login(options, jira_env, command_cat, com, logger) issue = com.run(command_cat, logger, jira_env, my_args) except Exception, e: print sys.exit('data error') if __name__ == '__main__': commit_text_verified = verify_commit_text(os.popen('hg tip --template "{desc}"')) #commit_text_verified = verify_commit_text(os.popen('hg log -r $1 --template "{desc}"')) if (commit_text_verified): sys.exit(0) else: print >> sys.stderr, ('[obey the rules!]') sys.exit(1); Is it possible to declare classes within functions in Python? A: Yes, just correct your indentation and that code should work. You'll be creating a new class each time the function is called. def CheckForJiraIssueRecord(object): class Options: pass options = Options() options.user = 'user' options.password = 'password' A: Yes, you can. Although each time the function is called, you will get a different class. A: Yes, however: 1) Each time through the function, Options becomes a separate class. Not that you will really be able to write code that exploits (or is broken by) this property, because 2) You can only instantiate the class via the function, unless you explicitly expose it to the global namespace somehow. 3) Assuming that you just need an object with those attributes - i.e. Jira doesn't care about your class interface beyond being able to do .user and .password - you don't really need to create a custom class at all: from collections import namedtuple def CheckForJiraIssueRecord(object): options = namedtuple('Options', 'user password')('user', 'password') # 'user password' are the field names, and ('user', 'password') are the # initialization values. This code creates a type similar to what you had # before, naming it 'Options' internally, but doesn't bind it to a variable. # As you were...
{ "language": "en", "url": "https://stackoverflow.com/questions/7506523", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Accessing a class constant using a simple variable which contains the name of the constant I'm trying to access a class constant in one of my classes: const MY_CONST = "value"; If I have a variable which holds the name of this constant like this: $myVar = "MY_CONST"; Can I access the value of MY_CONST somehow? self::$myVar does not work obviously because it is for static properties. Variable variables does not work either. A: There is no syntax for that, but you can use an explicit lookup: print constant("classname::$myConst"); I believe it also works with self::. A: Can I access the value of MY_CONST somehow? self::MY_CONST If you want to access is dynamically, you can use the reflection API Docs: $myvar = 'MY_CONST'; $class = new ReflectionClass(self); $const = $class->getConstant($myVar); The benefit with the reflection API can be that you can get all constants at once (getConstants). If you dislike the reflection API because you don't wanna use it, an alternative is the constant function (Demo): $myvar = 'MY_CONST'; class foo {const MY_CONST = 'bar';} define('self', 'foo'); echo constant(self.'::'.$myvar); A: Just a note for Reflection: the constructor for ReflectionClass must receive the full path of the class for its parameter. This means that just setting the string 'A' as a constructor parameter may not work in some cases. To avoid this problem, when using ReflectionClass you will be better if you do this: $classA = new A(); $name_classA = get_class($classA); $ref = new ReflectionClass(get_class($name_classA)); $constName = 'MY_CONST'; echo $ref->getConstant($constName); Function get_class will give you the full path of a class whenever you are in the code. Missing the full path may result in a "Class not found" PHP error. A: There are two ways to do this: using the constant function or using reflection. Constant Function The constant function works with constants declared through define as well as class constants: class A { const MY_CONST = 'myval'; static function test() { $c = 'MY_CONST'; return constant('self::'. $c); } } echo A::test(); // output: myval Reflection Class A second, more laborious way, would be through reflection: $ref = new ReflectionClass('A'); $constName = 'MY_CONST'; echo $ref->getConstant($constName); // output: myval A: have you tried $myVar = MY_CONST or $myVar = $MY_CONST
{ "language": "en", "url": "https://stackoverflow.com/questions/7506530", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "78" }
Q: How to set width with 2 div's using pixels and percents I have this example here. I'd like you to follow these steps: * *resize your browser window to less than 950 pixels wide. *now scroll to your right with the horizontal scroll-bar. *now you will notice that the grey bar (div) stops short and does not continue to the right edge of the page. I want to know how to fix it so the grey bar continues across the whole page. A: Instead of using css to set your bgcolor and border, use an image 1px wide and however high you need it to be. `background:url('images/bg.gif') repeat-x;` Be sure to include a 1px bottom border inside your bg image. A: Use min-width on the bar itself with the same width as the content in it... I don't know what kind of cross browser compatiblity you want but this should work in IE7 > . Any more would make this a lot more complex. Example here: http://jsfiddle.net/sg3s/hrN5F/ Edit, this might solve it for older versions of IE too, can't test it though http://jsfiddle.net/sg3s/hrN5F/2/
{ "language": "en", "url": "https://stackoverflow.com/questions/7506535", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: scrollTo with easing and a callback function Here is my code thus far: $('.my_button').click(function() { $.scrollTo( '#my_anchor', 1200, {easing:'easeInOutExpo'}, function() { // function not working here }); }); The callback function worked previously, but since I changed to the scrollTo method with easing, it doesn't any more! Just to make it clear I only need to know how to get my callback function working again, everything else is fine. A: There is no forth parameter, but the third parameter (settings) accepts an onAfter callback $.scrollTo( '#my_anchor', 1200, {easing:'easeInOutExpo', onAfter: function() { }}); from the source code on settings: * @param {Object,Function} settings Optional set of settings or the onAfter callback. * @option {String} axis Which axis must be scrolled, use 'x', 'y', 'xy' or 'yx'. * @option {Number} duration The OVERALL length of the animation. * @option {String} easing The easing method for the animation. * @option {Boolean} margin If true, the margin of the target element will be deducted from the final position. * @option {Object, Number} offset Add/deduct from the end position. One number for both axes or { top:x, left:y }. * @option {Object, Number} over Add/deduct the height/width multiplied by 'over', can be { top:x, left:y } when using both axes. * @option {Boolean} queue If true, and both axis are given, the 2nd axis will only be animated after the first one ends. * @option {Function} onAfter Function to be called after the scrolling ends. * @option {Function} onAfterFirst If queuing is activated, this function will be called after the first scrolling ends.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506538", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Redirecting a SAML protocol request to an ID Provider (whr equivalent?) SHORT: Is there a "whr" equivalent in SAML-P 2.0? LONG: We are implementing a Federated Provider security token service using ADFS 2.0. One of our replying parties will need the SAML 2.0 protocol. ADFS supports SAML-P 2.0 but I am not sure what to tell the relying party to specify in the SAML request to forward the request to the proper Identity provider. When using WS-Federation you can simply attach the "whr" attribute to the request query string and it will use that value to redirect. Does SAML-P have an equivalent? A: Maybe you could try with the RelayState parameter. Hope it helps, Luis
{ "language": "en", "url": "https://stackoverflow.com/questions/7506555", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Just so lost... ViewSwitcher? Create an Activity then add to ViewSwitcher? I'm new to Android and find it brutal (there seems to be an near infinite number of details and dependencies to remember). Anywho, I got the TextSwitcher1 example app working, which uses ViewSwitcher. I'm assuming ViewSwitcher is the way to go, need to either display a map or a table, user can pick, and switch back and forth. So I created my MapActivity in another application, seems to work. Next integrate into main app. So, call View v = findViewById(R.layout.mapview); and then mSwitcher.addView(v); except "v" is null. Why? Do I create the activity? But I don't want to show it yet. Is there such a call as "create activity but hide it until needed"? Or am I barking up the wrong tree? Thanks for any insight. A: The findViewById function returns a View based on an ID resource (R.id.something) for whatever view you have loaded in your activity (using setContentView(R.layout.main)). In your sample code, you're using a layout resource (R.layout.mapview). You should inflate the XML file, which will return a View that you can use to add to the ViewSwitcher. Example Code: LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v = vi.inflate(R.layout.mapview, null); mSwitcher.addView(v); However, you should be able to define everything in your XML file and not have to manually add the pages to your ViewSwitcher. Here's some example code on how to do that: http://inphamousdevelopment.wordpress.com/2010/10/11/using-a-viewswitcher-in-your-android-xml-layouts/
{ "language": "en", "url": "https://stackoverflow.com/questions/7506556", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to validate and enforce commit message in Mercurial? What are all steps required to validate commit message with set of regular expressions? We want to work in semi-centralized set-up so I need a solution for the developer clone (local repository) and for our central clone (global repository). I read about Mercurial Hooks but I am a little bit lost how to put all things together. For local repository I need a way to distribute validation script across my developers. I know that hooks do not propagate when cloning so I need to a way to "enable" them in each fresh clone. It would be done as a part of our PrepareEnvironement.bat script that we run anyway on each clean clone. To be double safe I need similar validation on my global repository. It should not be possible to push into global repository commit that are not validating. I can configure it manually - it is one time job. I am on Windows so installing anything except TortoiseHG should not be required. It was already a fight to get Mercurial deployed. Any other dependencies are not welcomed. A: You can use the Spellcheck example as a starting point. In each developer's configuration, you need to use the following hooks: pretxnchangegroup - Runs after a group of changesets has been brought into local from another repository, but before it becomes permanent. pretxncommit - Runs after a new changeset has been created in local, but before it becomes permanent. For the centralized repo, I think you only need the pretxnchangegroup hook unless commits can happen on the server, too. However, you will need the Histedit extension for each of the developers if the remote repo is the one rejecting one or more of the changesets being pushed. This extension allows them to "edit" already committed changesets. I would think in most cases, the local hooks will catch the issue, but like you said, "just in case." More details about handling events with hooks can be found in the Hg Book.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506559", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: NHibernate 3 QueryOver one to many I have this nhibernate query var session = SessionFactory.GetCurrentSession(); var users = session.QueryOver<User>() .Where(u => u.Enabled) .WhereRestrictionOn(u=>u.Orders).IsNull .Inner.JoinQueryOver<Foo>(a => a.Foos).Where(c => c.Enabled) .Inner.JoinQueryOver<Bar>(m => m.Bars).Where(m => m.Enabled) .TransformUsing(new DistinctRootEntityResultTransformer()) .List(); WhereRestrictionOn Orders doesn't work but I am trying to ensure these users have zero orders but have Foos and Bars Can anyone help with a way to do it in NHibernate? Update: Here is how I changed this so far - seems to work var session = SessionFactory.GetCurrentSession(); User rawUser = null; var existing = QueryOver.Of<Order>().Where(x => x.UserID == rawUser.UserID).Select(x=>x.User); var users = session.QueryOver<User>(() => rawUser) .Where(u => u.Enabled) .WithSubquery.WhereNotExists(existing) .Inner.JoinQueryOver<Foo>(a => a.Foos).Where(c => c.Enabled) .Inner.JoinQueryOver<Bar>(m => m.Bars).Where(m => m.Enabled) .TransformUsing(new DistinctRootEntityResultTransformer()) .List();
{ "language": "en", "url": "https://stackoverflow.com/questions/7506561", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to extract string between 2 markers using Regex in .NET? I have a source to a web page and I need to extract the body. So anything between </head><body> and </body></html>. I've tried the following with no success: var match = Regex.Match(output, @"(?<=\</head\>\<body\>)(.*?)(?=\</body\>\</html\>)"); It finds a string but cuts it off long before </body></html>. I escaped characters based on the RegEx cheat sheet. What am i missing? A: I'd recommend using the HtmlAgilityPack instead - parsing HTML with regular expressions is very, very fragile. The latest version even supports Linq so you can get your content like this: HtmlWeb web = new HtmlWeb(); HtmlDocument doc = web.Load("http://stackoverflow.com"); string html = doc.DocumentNode.Descendants("body").Single().InnerHtml; A: Regex is not meant for such html handling, as many here would say. Without having your sample web page / html, I can only say that try removing the non-greedy ? quantifier in (.*?) and try. After all, a html page will have only one head and body. A: Though regexes are definitely not the best tool for this task, there are a few suggestions and points I would like to make: * *un-escape the angle brackets - with the @ before your string, they are going through to the regex and they do not need to be escaped for a .NET regex *with your regex, you need to make sure that the head/body tag combinations do not have any white-space between them. *with your regex, the body tag cannot have any attributes. I would suggest something more like: (?<=</head>\s*<body(\s[^>]*)?>)(.*?)(?=</body>\s*</html>) this seems to work for me on the source of this page! A: As the others have said, the correct way to handle this is with an HTML-specific tool. I just want to point out some problems with that cheat-sheet. First, it's wrong about angle brackets: you do not need to escape them. In fact, it's wrong twice: it also says \< and \> match word boundaries, which is both incorrect for .NET, and incompatible with the advice about escaping angle brackets. That cheat-sheet is just a random collection of regex syntax elements; most of them will work in most flavors, but many are guaranteed not to work in your particular flavor, whatever it happens to be. I recommend you disregard it and rely instead on .NET-specific documents or Regular-Expressions.info. The books Mastering Regular Expressions and Regular Expressions Cookbook are both excellent, too. As for your regex, I don't see how it could behave the way you say it does. If it were going to fail, I would expect it to fail completely. Does your HTML document contain a CDATA section or SGML comment with </body></html> inside it? Or is it really two or more HTML documents run together?
{ "language": "en", "url": "https://stackoverflow.com/questions/7506573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Should I use a wordpress hook to replace a file? I'm having a little trouble deciding how I should be implementing hooks in wordpress. I'm currently using a child theme and in the single.php file of the parent theme there is a function <?php con_get_sharebox(); ?> that gets the contents of a file sharebox.php. Now the sharebox.php file is the file I'd like to edit but I don't know how to do this using hooks. I tried simply adding a different sharebox.php to my child theme but because its not part of the standard theme files I don't think it gets loaded. Any ideas on what I can do?
{ "language": "en", "url": "https://stackoverflow.com/questions/7506574", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sharing memory-based data in Google App Engine I'm loosely considering using Google App Engine for some Java server hosting, however I've come across what seems to be a bit of a problem whilst reading some of the docs. Most servers that I've ever written, and certainly the one I have in mind, require some form of memory-based storage that persists between sessions, however GAE seems to provide no mechanism for this. * *Data can be stored as static objects but an app may use multiple servers and the data cannot be shared between the servers. *There is memcache, which is shared, but since this is a cache it is not reliable. *This leaves only the datastore, which would work perfectly, but is far too slow. What I actually need is a high performance (ie. memory-based) store that is accessible to, and consistent for, all client requests. In this case it is to provide a specialized locking and synchronization mechanism that sits in front of the datastore. It seems to me that there is a big gap in the functionality here. Or maybe I am missing something? Any ideas or suggestions? A: Static data (data you upload along with your app) is visible, read-only, to all instances. To share data between instances, use the datastore. Where low-latency is important, cache in memcache. Those are the basic options. Reading out of the datastore is pretty fast, it's only writes you'll need to concern yourself with, and those can be mitigated by making sure that any entity properties that you don't need to query against are unindexed. Another option, if it fits your budget, is to run your own cache in an always-on backend server.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506576", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Should I write a new application in Flex4/Spark if performance is a bigger consideration than skinning? I've worked extensively with MX and Spark frameworks and both work fine for me. I am about to start a very large project in Flex where speed and file size are going to be critical factors. I am not going to use Adobe Catalyst. Is there any reason I should use Spark for this application rather than MX? A: Is there any reason I should use Spark for this application rather than MX? Adobe has stated that Spark is the future. The MX line is receiving no new components; and many expect to the be deprecated at some future point. Spark also provides a significantly more flexible skinning architecture. Spark components are architected in a way that is supposed to be more light weight; sort of like a "Pay As You Go" architecture, so you aren't dragging lots of functionality along that you don't need. A good example of this is that scrollbars are separate from containers. Spark also provides you with greater Flexibility for deployments. Only spark components are supported on Mobile devices, for example. If speed and file size are critical factors, you may want to reconsider your use of Flex, though. There are a bunch of alternate ActionScript frameworks such as Reflex, that are written for simplicity and performance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506577", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Java color detection I am implementing algorithm in java which select a portion of image as marker. My problem is 1) After selecting the marker area, how do i get the specific mean value of marker color in RGB as the number of pixels with a small difference in color. 2) How can i find marker value, meaning the threshold value for the color, based on the previous marker selection. Please provide an algorithm and if posssible, an implementation in java. Thanks in advance. A: I'm not sure what you tried, and where you're stuck, but here goes: * *To get a mean color your best bet is to try to find the median value for the three channels (R, G and B) separately and use that as the mean. Due to specific qualities of the RGB color space, the mean is very vulnerable to outliers, the median less so. *I assume you want to select all colors that are similar to your marker color. To do that you could select all pixels where the color is less small euclidean distance to your median RGB color selected above. If this does not work for you you could look into alternative colorspaces. But I think the above should be enough.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506579", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Div height is not adjusting when RadMultiPage loads a long page My asp.net page has a div (#multipage) that contains a Telerik MultiPage control. For those who are not familiar with Telerik controls think of it as a iFrame that loads various other page in response to the user's clicks on a tab control. My problem is that one of my pages loaded by the multipage control is a long one. And when it loads the browser wraps it with scrollbars rather than expanding the height of the div that contains it. I can't figure out why this is happening. I suppressed scrollbars in the control and did my best to configure my css such that the height of the div is dynamic. Below is an abbreviated version of my asp.net markup showing only those elements that are related to layout. Can someone please tell me what I need to do to make the height of the multipage div dynamic? <head runat="server"> <style type="text/css"> * { margin: 0; } html, body { height: auto; height: 100%; } .wrapper { min-height: 100%; height: auto !important; height: 100%; margin: 0 auto -142px; /* the bottom margin is the negative value of the footer's height */ } .footer, .push { height: 142px; /* .push must be the same height as .footer */ background-color: #144e77; color: #fff; font-family: DejaVuSansBook, Sans-Serif; } #multipage { min-height: 100%; height: auto !important; height: 100%; } </style> </head> <body style="background:url(AuthImages/bg.jpg) repeat; margin:0px 0px 0px 0px"> <form id="form1" runat="server"> <div class="wrapper"> <div id="header_container"> <div id="header" style="width:100%; height:75px;"> <div id="logo" style="float:left"></div> <div id="welcome" style="float:right; margin-right: 5px; margin-top:5px;"> </div> </div> </div> <div id="tabs" style="width:100%; height:25px; border-bottom: 2px solid #144e77"> <telerik:RadTabStrip ID="RadTabStrip1" runat="server" SelectedIndex="0" Width="100%" MultiPageID="RadMultiPage1"> <Tabs> <!--tabs are here--> </Tabs> </telerik:RadTabStrip> </div> <div id="multipage"> <telerik:RadMultiPage ID="RadMultiPage1" runat="server" ScrollBars="None"> <!--RadPageViews are here--> </div> <div class="push"></div> </div> <div class="footer"> </div> </form> A: There is no way via CSS to make a dynamic frame height. I am not familiar with ASP nor RadMultiPage, however one solution is to use a javascript+css based tab navigation system that dynamically adjusts the height of the content container to match that of the height required/created by the content. There's an informal list of a few here. I seem to remember this one as being useful. A: Go ahead and create a fresh Telerik site and copy the code below over the existing html to /html section. <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <style type="text/css"> * { margin: 0; } html, body { height: auto; height: 100%; } .wrapper { min-height: 100%; height: auto !important; height: 100%; margin: 0 auto -142px; /* the bottom margin is the negative value of the footer's height */ } .footer, .push { height: 142px; /* .push must be the same height as .footer */ background-color: #144e77; color: #fff; font-family: DejaVuSansBook, Sans-Serif; } #multipage { min-height: 100%; height: auto !important; background-color: Gray; width: 100%; } </style> </head> <body> <form id="form1" runat="server"> <telerik:RadScriptManager ID="RadScriptManager1" runat="server"> </telerik:RadScriptManager> <div class="wrapper"> <div id="header_container"> <div id="header" style="width:100%; height:75px;"> <div id="logo" style="float:left"></div> <div id="welcome" style="float:right; margin-right: 5px; margin-top:5px;"> </div> </div> </div> <div id="tabs" style="width:100%; height:25px; border-bottom: 2px solid #144e77"> </div> <div id="multipage" style="width: 100%"> <telerik:RadMultiPage ID="RadMultiPage1" runat="server" ScrollBars="None" SelectedIndex="0" Width="742px"> <!--RadPageViews are here--> <telerik:RadPageView ID="RadPageView1" runat="server"> <asp:Calendar ID="Calendar1" runat="server"></asp:Calendar> </telerik:RadPageView> <telerik:RadPageView ID="RadPageView2" runat="server"> <asp:TextBox ID="TextBox1" runat="server" Height="461px"></asp:TextBox> </telerik:RadPageView> </telerik:RadMultiPage> </div> <div class="push"> </div> </div> <div class="footer"> <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" /> </div> </form> </body> </html> Then add this to the code behind: protected void Button1_Click(object sender, EventArgs e) { RadMultiPage1.SelectedIndex = 1; } Run it and tell me if that works. As I recall I had to close a few tags that you left open in your code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506584", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why are objects apparently cloned by collection initializer for List<>?> In the following code, why is pdList[0] null while _propertyDetails is a properly instantiated object? I was under the impression that I'm adding a reference to pdList that points to the same object as _propertyDetails, so after instantiating this object, both references should be non-null? PropertyDetailsModel _propertyDetails = null; var pdList = new List<PropertyDetailsModel> { _propertyDetails }; _propertyDetails = PropertyDetailsModel.Read(PropertyId); Forgive me if I'm missing something basic; I've been battling to narrow my problem down to this issue for several hours, and my brain is tired. A: When you initialise the list, it is not _propertyDetails that goes into the list, but the thing that _propertyDetails is currently a reference to (which is null in this example, but the point remains). Making _propertyDetails refer to a different thing later doesn't change what's in the list. A: It's (apparently) a reference type, so when you create pdList, the reference gets copied, but it is null at that point. Assigning to _propertyDetails later does not change the null reference that's already in pdList. A: _propertyDetails is not an properly instantiated object. It's not an object at all. It is a reference which points to nothing which is called null in C#. To get an object, you would have to write something like PropertyDetailsModel _propertyDetails = new PropertyDetailsModel(); A: As others have said, you're getting confused between a variable and its value. You don't need to use lists to demonstrate this - it's equivalent to this code: string foo = null; string bar = foo; foo = "Hello"; Console.WriteLine(bar); // Empty, as the value of bar is null Changing the value of a variable is not the same thing as changing the data within an object that the variable refers to.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506585", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why does listview fire event indicating that checked item is unchecked after adding I'm adding items to a listview (c# winforms app) via the following code: var IT = new ListViewItem(Term); IT.Checked = true; MyListView.Items.Add(IT); However, immediately after adding the item I receive an event which indicates that the item isn't checked (e.Item.Checked is false). I then receive a subsequent event which indicates that it is checked (e.Item.Checked is true). Why am I receiving the first event? Is the checked property being set to false for some reason when I add the item to the list? Seems odd given that I'm setting the checked status to true prior to adding it to my event. Any help greatly appreciated. Thanks in advance. A: I was experiencing the same dilema and solved it a bit more locally than in jdavies's answer, by simply filtering out the initial "non-checked state not caused by the user" as follows void listView_ItemChecked(object sender, ItemCheckedEventArgs e) { if (!e.item.Checked && !e.item.Focused) return; // ignore this event // // do something } A: It seems as though when each ListViewItem's CheckBox is added to the ListView it is initially set as unchecked which fires the ItemChecked event. In your case the CheckBox is then set as checked to match IT.Checked = true; which fires the event again. This seems to be by design and I do not think there is a method of stopping these events from firing upon load. One work around (albeit a bit of a hack) would be to check the FocusedItem property of the ListView, as this is null until the ListView is loaded and retains a reference to a ListItem there after. void listView1_ItemChecked(object sender, ItemCheckedEventArgs e) { if (listView1.FocusedItem != null) { //Do something } } Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506588", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: ASP.NET MVC: What part of controller action logic should we/should not move to attributes? Let's assume that we have a controller with some action which could look like: [HttpPost, Authorize] public ActionResult Update(Guid itemId) { var item = repository.GetById(itemId); if (item == null) return NotFoundResult(); //Do something with item return View(); } We already have applied an Authorize attribute to be sure that only some specific users can perform our action. We could also move the following block var item = repository.GetById(itemId); if (item == null) return NotFoundResult(); to another attribute and apply it to our action. There are another actions where we could extract some specific pieces of logic to attribute and apply them to our actions again and again. Here comes my question: when should we do it and when we should not? Is it actually a good thing to move such kind of logic to action method attributes? I've came to this question when I was reviewing unit tests for some project. I was actually looking for code documentation and it was strange for me not seeing what should controller action do if, for example, item was not found. I've found this part in attributes unit tests, but is this actually attribute's responsibility? I can understand Authorize attribute, it is actually another layer, but what about the logic that I've described above? Is it controller's action responsibility to work with it or ..? Thanks in advance for any comments :) A: If you want to run logic like this for a group of actions, you can override the OnActionExecuting method to perform the check. Creating an attribute would be difficult, as you would also need to create a base controller and write some reflection code to inspect the action method to see if the attribute exists, then act on it. protected override void OnActionExecuting(ActionExecutingContext ctx) { if(!ctx.ActionDescriptor.ActionName.StartsWith("Create")) { var item = repository.GetById(itemId); if (item == null) ctx.Result = NotFoundResult(); } } A: Attributes are used for various things in ASP.net MVC (for example filtering or exception handling). I would however not move logic like this to attributes as this is basic logic for the action you're executing. Moving this code to attributes will only make it harder to find what the action is actually doing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506593", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Haskell: FIFO monad Is there a standard (or at least commonly used) package with a monad for FIFO queues? I read about this one in a paper a while ago, and I've used it a couple times, but I'd like to stop reimplementing wheels (it's fun, but unproductive). A: I don't think there is. I would use a State monad with a Seq container as state. A: There's a nifty version of corecursive queues on hackage: http://hackage.haskell.org/package/control-monad-queue I wouldn't call it standard by any means, but it certainly reflects a fair amount of work and testing. The linked monad reader article is a really good read too.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506594", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to return an array made in a child jQuery function from the parent function in Javascript? I'm using a jQuery json function inside another function, how can I return an array made in the jQuery function as the return value of my parent function? this is the basic setup function getFlickrSet(flickr_photoset_id){ var images = []; images = $.getJSON(url, function(data){ return data; // I HAVE THE DATA HERE }; return images // I HAVE NO DATA HERE } var myImages = getFlickrSet(23409823423423); alert(myImages); // this gives me nothing I have set up an example on jsfiddle right here, if you could tell me where my code is wrong, I would greatly appreciate it. Thank you! A: You can't. Instead, pass in a function: function getFlickrSet(flickr_photoset_id, when_ready){ var images = []; $.getJSON(url, function(data){ // prepare images when_ready( images ); }); } getFlickrSet(nnnn, function(images) { alert(images); }); Why can't you do that? Because the "$.getJSON()" call is asynchronous. By the time that the callback function is called (where you wrote, "I HAVE THE DATA HERE"), the outer function has returned already. You can't make the browser wait for that call to complete, so instead you design the API such that code can be passed in and run later when the result is available. A: Well, Ajax is asynchronous (that's what the 'A' stands for), so you must do this in an asynchronous way, which boils down to callbacks. What you need to do is pass a callback function to your outer function that you want to be called ("called back," if you will) when the Ajax request completes. You could just give it 'alert' like this: function getFlickrSet(flickr_photoset_id) { images = $.getJSON(url, alert); // <-- just the name of the function, no () } var myImages = getFlickrSet(23409823423423); // => An alert pops up with the data! ...but more likely you'd write something like this: function doSomethingWithData(data) { // we'll use this later alert(data); // or whatever you want } function getFlickrSet(flickr_photoset_id, callback) { // new parameter here for a function ------^ // to be given here -------v images = $.getJSON(url, callback); return images // I HAVE NO DATA HERE } var myImages = getFlickrSet(23409823423423, doSomethingWithData); // => Your function `doSomethingWithData` will be called the data as a parameter // when the $.getJSON request returns.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506603", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }