Search Results

Search found 2126 results on 86 pages for 'wrapper'.

Page 74/86 | < Previous Page | 70 71 72 73 74 75 76 77 78 79 80 81  | Next Page >

  • facebook app using fbml displays nothing

    - by fusion
    i've made an app in php and html and trying to integrate it with fb. the app on my website is using jquery, but knowing that fbml doesn't support jquery, i've tried to instead use fbjqry. this doesn't work either. i'm not sure where i'm going wrong. /////////////// index.php: <?php // Copyright 2007 Facebook Corp. All Rights Reserved. require_once 'config_fb.php'; //***** Greet the currently logged-in user! echo "<p>Hello, <fb:name uid=\"$user_id\" useyou=\"false\" />!</p>"; include 'quote.html'; ?> ///////////////// quote.html: <!DOCTYPE html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <link rel="stylesheet" type="text/css" href="css/jquote.css" /> <!--<script type="text/javascript" src="scripts/jquery-1.4.2.js"></script>--> <script type="text/javascript" src="fbjqry/utility.js"></script> <script type="text/javascript" src="fbjqry/fjqry.js"></script> <script type="text/javascript"> // On page load, fill the box with content. $(document).ready(function() { $("#quoteContainer").load("quote.php"); }); var auto_refresh = setInterval( function () { $('#quoteContainer').load('quote.php'); }, 5000); // refresh every 10000 milliseconds </script> </head> <div id="wrapper"> <div class="header">&nbsp;Quote of the Day</div> <div id="quoteContainer"> </div> </div> </html> //// from the above file it should take quotes from quote.php and display it, but it doesn't display anything. it seems as though it isn't reading from the quote.php file. is the command of fbjqry different from jquery? if i use iframes instead of fbml, everything loads correctly except that i'd like tab/profile box for this app, which iframes doesn't have.

    Read the article

  • how to create a system-wide independent universal counter object primarily for Database keys?

    - by andora
    I would like to create/use a system-wide independent universal 'counter object' that can be called via COM in a thread-safe manner. The counter object will be passed an ID to identify which counter to return, handle the counting, 'persist' the count (occasionally), have reasonable performance (as fast as possible) perhaps capable of 1000 counts per second or better (1mS) and be accessible cross-process/out-of-process. The current count status must be persisted between object restarts/shutdowns. The counter object is liklely to be a 'singleton' type object implemented in some form of free-threaded dictionary, containing maybe 10 counters (perhaps 50 max). The count needs to be monotonic and consistent, (ie: guaranteed unique sequential values). Each counter should have a few methods, like reset, inc, dec, set, clear, remove. As a luxury, I would like to have a variable-increment (ie: 'step by' value). To support thread-safefty, perhaps some sorm of critical-section or mutex call. It just needs to return a long/4byte signed integer. I really want something that can be called from anywhere, including VBScript, so I figure COM is my preferred solution. The primary use of this is for database keys. I am unable to use autoinc or guid type keys and have ruled out database-generated counting systems at this point. I've spent days researching this and I have really struggled to find a solution. The best I can find is a free-threaded dictionary object that can be instantiated using COM+ from Motobit - it seems to offer all the 'basics' and I guess I could create some form of wrapper for this. So, here are my questions: Does such a 'general purpose counter-object already exist? Can you direct me to it? (MS did do an IIS/ASP object called 'MSWC.Counter' but this isn't 'cross-process'/ out-of-process component and isn't thread-safe. (but if it was, it would do!) What is the best way of creating such a Component? (I'd prefer VB6 right-now, [don't ask!] but can do in VB.NET2005 if I had to). I don't have the skills/knowledge/tools to use anything else. I am desparate for a workable solution. I need specific guidance! If anybody can code something up for me I am prepared to pay for it.

    Read the article

  • Stop output of image if no record - paperclip - Ruby on rails

    - by bgadoci
    I have just installed paperclip into my ruby on rails blog application. Everything is working great...too great. I am trying to figure out how to tell paperclip not to output anything if there is no record in the table so that I don't have broken image links everywhere. How, and where, do I do this? Here is my code: class Post < ActiveRecord::Base has_attached_file :photo, :styles => { :small => "150x150"} validates_presence_of :body, :title has_many :comments, :dependent => :destroy has_many :tags, :dependent => :destroy has_many :ugtags, :dependent => :destroy has_many :votes, :dependent => :destroy belongs_to :user after_create :self_vote def self_vote # I am assuming you have a user_id field in `posts` and `votes` table. self.votes.create(:user => self.user) end cattr_reader :per_page @@per_page = 10 end View <% div_for post do %> <div id="post-wrapper"> <div id="post-photo"> <%= image_tag post.photo.url(:small) %> </div> <h2><%= link_to_unless_current h(post.title), post %></h2> <div class="light-color"> <i>Posted <%= time_ago_in_words(post.created_at) %></i> ago </div> <%= simple_format truncate(post.body, :length => 600) %> <div id="post-options"> <%= link_to "Read More >>", post %> | <%= link_to "Comments (#{post.comments.count})", post %> | <%= link_to "Strings (#{post.tags.count})", post %> | <%= link_to "Contributions (#{post.ugtags.count})", post %> | <%= link_to "Likes (#{post.votes.count})", post %> </div> </div> <% end %>

    Read the article

  • How can I create the XML::Simple data structure using a Perl XML SAX parser?

    - by DVK
    Summary: I am looking a fast XML parser (most likely a wrapper around some standard SAX parser) which will produce per-record data structure 100% identical to those produced by XML::Simple. Details: We have a large code infrastructure which depends on processing records one-by-one and expects the record to be a data structure in a format produced by XML::Simple since it always used XML::Simple since early Jurassic era. An example simple XML is: <root> <rec><f1>v1</f1><f2>v2</f2></rec> <rec><f1>v1b</f1><f2>v2b</f2></rec> <rec><f1>v1c</f1><f2>v2c</f2></rec> </root> And example rough code is: sub process_record { my ($obj, $record_hash) = @_; # do_stuff } my $records = XML::Simple->XMLin(@args)->{root}; foreach my $record (@$records) { $obj->process_record($record) }; As everyone knows XML::Simple is, well, simple. And more importantly, it is very slow and a memory hog—due to being a DOM parser and needing to build/store 100% of data in memory. So, it's not the best tool for parsing an XML file consisting of large amount of small records record-by-record. However, re-writing the entire code (which consist of large amount of "process_record"-like methods) to work with standard SAX parser seems like an big task not worth the resources, even at the cost of living with XML::Simple. I'm looking for an existing module which will probably be based on a SAX parser (or anything fast with small memory footprint) which can be used to produce $record hashrefs one by one based on the XML pictured above that can be passed to $obj->process_record($record) and be 100% identical to what XML::Simple's hashrefs would have been. I don't care much what the interface of the new module is; e.g whether I need to call next_record() or give it a callback coderef accepting a record.

    Read the article

  • Passing objects to a UITypeEditor

    - by Kath
    I am currently hoping to use a PropertyGrid to allow users to edit some of my classes, however I've hit a wall with passing objects to the UITypeEditor(s) they use. When the user presses the drop down I want to show a listbox of already loaded textures to choose from, if they want to use a texture the application hasn't loaded yet they can click a button to choose one from a file dialog. In case I make no sense here a mock of the form: . My problem: To fill the listbox I need access to the class that manages the list of resources from the UITypeEditor. Now I've solved this problem for my own classes by giving them a reference on creation to their managing object. In the UITypeEditor I then use that reference to access what I need. However I can't do this for classes I haven't written, such as the XNA Texture2D class. Here are what the classes I'm using look like: class StaticGeometryChunk { // Geometry data to draw with. Contains a reference to its managing // class for use in its UITypeEditor. public GeometryData { get; set; } .... } class Material { // These are XNA classes. I can't just add a reference to its managing // class (I think?). public Texture2D Texture1 { get; set; } public Texture2D Texture2 { get; set; } .... } I've been looking at my options and they seem to be: Make the managing classes static. I don't really want to do this. There are several managing classes as each resource is loaded differently. There are also classes that need to be created before these and are passed in. Make the managing classes singletons. I don't really want to do this either. It seems like a quick and dirty way to "hide" the problem instead of "solve" it. I also might want the option of having several managing classes in the future which the singletons eliminate. Create a wrapper class which holds the reference to a managing class and its target (such as the XNA Texture2D). This is currently what I'm thinking of doing. Its would be quite simple and quick to do but something about it nags me but I don't know what. Any thoughts on the above or other methods to pass what I need into the UITypeEditor? Thank you for reading.

    Read the article

  • Neo4j 1.9.4 (REST Server,CYPHER) performance issue

    - by user2968943
    I have Neo4j 1.9.4 installed on 24 core 24Gb ram (centos) machine and for most queries CPU usage spikes goes to 200% with only few concurrent requests. Domain: some sort of social application where few types of nodes(profiles) with 3-30 text/array properties and 36 relationship types with at least 3 properties. Most of nodes currently has ~300-500 relationships. Current data set footprint(from console): LogicalLogSize=4294907 (32MB) ArrayStoreSize=1675520 (12MB) NodeStoreSize=1342170 (10MB) PropertyStoreSize=1739548 (13MB) RelationshipStoreSize=6395202 (48MB) StringStoreSize=1478400 (11MB) which is IMHO really small. most queries looks like this one(with more or less WITH .. MATCH .. statements and few queries with variable length relations but the often fast): START targetUser=node({id}), currentUser=node({current}) MATCH targetUser-[contact:InContactsRelation]->n, n-[:InLocationRelation]->l, n-[:InCategoryRelation]->c WITH currentUser, targetUser,n, l,c, contact.fav is not null as inFavorites MATCH n<-[followers?:InContactsRelation]-() WITH currentUser, targetUser,n, l,c,inFavorites, COUNT(followers) as numFollowers RETURN id(n) as id, n.name? as name, n.title? as title, n._class as _class, n.avatar? as avatar, n.avatar_type? as avatar_type, l.name as location__name, c.name as category__name, true as isInContacts, inFavorites as isInFavorites, numFollowers it runs in ~1s-3s(for first run) and ~1s-70ms (for consecutive and it depends on query) and there is about 5-10 queries runs for each impression. Another interesting behavior is when i try run query from console(neo4j) on my local machine many consecutive times(just press ctrl+enter for few seconds) it has almost constant execution time but when i do it on server it goes slower exponentially and i guess it somehow related with my problem. Problem: So my problem is that neo4j is very CPU greedy(for 24 core machine its may be not an issue but its obviously overkill for small project). First time i used AWS EC2 m1.large instance but over all performance was bad, during testing, CPU always was over 100%. Some relevant parts of configuration: neostore.nodestore.db.mapped_memory=1280M wrapper.java.maxmemory=8192 note: I already tried configuration where all memory related parameters where HIGH and it didn't worked(no change at all). Question: Where to digg? configuration? scheme? queries? what i'm doing wrong? if need more info(logs, configs) just ask ;)

    Read the article

  • C# Property Access vs Interface Implementation

    - by ehdv
    I'm writing a class to represent a Pivot Collection, the root object recognized by Pivot. A Collection has several attributes, a list of facet categories (each represented by a FacetCategory object) and a list of items (each represented by a PivotItem object). Therefore, an extremely simplified Collection reads: public class Collection { private List<FacetCategory> categories; private List<PivotItem> items; // other attributes } What I'm unsure of is how to properly grant access to those two lists. Because declaration order of both facet categories and items is visible to the user, I can't use sets, but the class also shouldn't allow duplicate categories or items. Furthermore, I'd like to make the Collection object as easy to use as possible. So my choices are: Have Collection implement IList<PivotItem> and have accessor methods for FacetCategory: In this case, one would add an item to Collection foo by writing foo.Add(bar). This works, but since a Collection is equally both kinds of list making it only pass as a list for one type (category or item) seems like a subpar solution. Create nested wrapper classes for List (CategoryList and ItemList). This has the advantage of making a consistent interface but the downside is that these properties would no longer be able to serve as lists (because I need to override the non-virtual Add method I have to implement IList rather than subclass List. Implicit casting wouldn't work because that would return the Add method to its normal behavior. Also, for reasons I can't figure out, IList is missing an AddRange method... public class Collection { private class CategoryList: IList<FacetCategory> { // ... } private readonly CategoryList categories = new CategoryList(); private readonly ItemList items = new ItemList(); public CategoryList FacetCategories { get { return categories; } set { categories.Clear(); categories.AddRange(value); } } public ItemList Items { get { return items; } set { items.Clear(); items.AddRange(value); } } } Finally, the third option is to combine options one and two, so that Collection implements IList<PivotItem> and has a property FacetCategories. Question: Which of these three is most appropriate, and why?

    Read the article

  • Passing Auth to API calls with Web Service References

    - by coffeeaddict
    I am new to web services. The last time I dealt with SOAP was when I created a bunch of wrapper classes that sent requests and received responses back per some response objects/classes I had created. So I had an object to send certain API requests and likewise a set of objects to hold the response back as an object so I could utilize that 3rd party API. Then someone came to me and said why not just use the wsdl and a web service. Ok, so today I went and created a "Service Reference". I see that this is what's called a "Proxy Class". You just instantiate an instance of this and then walla you have access to all the methods from the wsdl. But this leaves me with auth questions. Back when I created my own classes manually, I had a class which exposed properties that I would set then access for things like signature, username, password that got sent along with the Http request that were required by whatever 3rd party API I was using to make API calls. But then with using a Service Reference, how then would I pass this information just like I had done in my custom classes? For instance I'm going to be working with the PayPal API. It requires you to send a signature and a few other pieces of information like username and password. // Determins if API call needs to use a session based URI string requestURI = UseAuthURI == true ? _requestURIAuthBased + aSessionID : _requestURI; byte[] data = XmlUtil.DocumentToBytes(doc); // Create the atual Request instance HttpWebRequest request = CreateWebRequest(requestURI, data.Length); So how do I pass username, password, signature, etc. when using web service references for each method call? Is it as simple as specifying it as a param to the method or do you use the .Credentials and .URL methods of your proxy class object? It seems to me Credentials means windows credentials but I could be wrong. Is it limited to that or can you use that to specify those required header values that PayPal expects with each method call/API request?

    Read the article

  • impress.js Navigation with active class

    - by ArtGoddess
    I would like to use impress.js in order to make a website, with a navigation bar. In each slide, the corresponding anchor or div must have an "active" class, in order to achieve a different link appearance. I have followed all instructions provided here: https://github.com/Ralt/impress.js/commit/f88feb8cae704ce27bd2168bdb77768f516ac2da#L2R605 but the "active" class on the correct menu must be added. This is the code that generates the menu items. How can I add for example the "active" class in the first link? /* ************************ MENU ***************************** */ // Capitalize first letter of string // @see http://stackoverflow.com/a/1026087/851498 var capitalize = function( str ) { return str.charAt(0).toUpperCase() + str.slice(1); } // `showMenu` API function creates the menu // It defines the names of each entry by the id capitalized. var showMenu = function() { // Create the menu wrapper and the element that will be cloned // for each entry. var menu = document.createElement('div'), el = document.createElement('div'); // Apply some classes menu.className = 'menu'; el.className = 'menu-item'; // Create an element that will be the "button" and append it // to the menu var button = document.createElement('div'); button.className = 'menu-button'; button.textContent = 'Menu'; menu.appendChild(button); // Now, for each div in #impress, add an entry to the menu [].forEach.call(byId('impress').firstElementChild.children, function( child, index ) { var newEl = el.cloneNode(), i = index + 1, text = i + '. ' + capitalize(child.id); // Set the text of the new element newEl.textContent = text; // Add an onclick event to the new element // We need to use a closure to make sure the index is correct (function( index ) { newEl.addEventListener('click', function() { goto(index); }); }( index )); // And append the new element to the menu menu.appendChild(newEl); }); // And append the menu to #impress document.body.appendChild(menu); }; Then, in each click it must be removed the active class on the current, and add it to the clicked element. // Remove the active class from the current active document.querySelector( '.active' )[ 0 ].classList.remove( 'active' ); // And add it to the clicked index byId('impress').firstElementChild.children[ index ].classList.add( 'active' ); Where do I have to apply this code? Thank you!

    Read the article

  • Image_tag .blank? - paperclip - Ruby on rails

    - by bgadoci
    I have just installed paperclip into my ruby on rails blog application. Everything is working great...too great. I am trying to figure out how to tell paperclip not to output anything if there is no record in the table so that I don't have broken image links everywhere. How, and where, do I do this? Here is my code: class Post < ActiveRecord::Base has_attached_file :photo, :styles => { :small => "150x150"} validates_presence_of :body, :title has_many :comments, :dependent => :destroy has_many :tags, :dependent => :destroy has_many :ugtags, :dependent => :destroy has_many :votes, :dependent => :destroy belongs_to :user after_create :self_vote def self_vote # I am assuming you have a user_id field in `posts` and `votes` table. self.votes.create(:user => self.user) end cattr_reader :per_page @@per_page = 10 end View <% div_for post do %> <div id="post-wrapper"> <div id="post-photo"> <%= image_tag post.photo.url(:small) %> </div> <h2><%= link_to_unless_current h(post.title), post %></h2> <div class="light-color"> <i>Posted <%= time_ago_in_words(post.created_at) %></i> ago </div> <%= simple_format truncate(post.body, :length => 600) %> <div id="post-options"> <%= link_to "Read More >>", post %> | <%= link_to "Comments (#{post.comments.count})", post %> | <%= link_to "Strings (#{post.tags.count})", post %> | <%= link_to "Contributions (#{post.ugtags.count})", post %> | <%= link_to "Likes (#{post.votes.count})", post %> </div> </div> <% end %>

    Read the article

  • Java DriverManager Always Assigns My Driver

    - by JGB146
    I am writing a driver to act as a wrapper around two separate MySQL connections (to distributed databases). Basically, the goal is to enable interaction with my driver for all applications instead of requiring the application to sort out which database holds the desired data. Most of the code for this is in place, but I'm having a problem in that when I attempt to create connections via the MySQL Driver, the DriverManager is returning an instance of my driver instead of the MySQL Driver. I'd appreciate any tips on what could be causing this and what could be done to fix it! Below is a few relevant snippets of code. I can provide more, but there's a lot, so I'd need to know what else you want to see. First, from MyDriver.java: public MyDriver() throws SQLException { DriverManager.registerDriver(this); } public Connection connect(String url, Properties info) throws SQLException { try { return new MyConnection(info); } catch (Exception e) { return null; } } public boolean acceptsURL(String url) throws SQLException { if (url.contains("jdbc:jgb://")) { return true; } return false; } It is my understanding that this acceptsURL function will dictate whether or not the DriverManager deems my driver a suitable fit for a given URL. Hence it should only be passing connections from my driver if the URL contains "jdbc:jgb://" right? Here's code from MyConnection.java: Connection c1 = null; Connection c2 = null; /** *Constructors */ public DDBSConnection (Properties info) throws SQLException, Exception { info.list(System.out); //included for testing Class.forName("com.mysql.jdbc.Driver").newInstance(); String url1 = "jdbc:mysql://server1.com/jgb"; String url2 = "jdbc:mysql://server2.com/jgb"; this.c1 = DriverManager.getConnection( url1, info.getProperty("username"), info.getProperty("password")); this.c2 = DriverManager.getConnection( url2, info.getProperty("username"), info.getProperty("password")); } And this tells me two things. First, the info.list() call confirms that the correct user and password are being sent. Second, because we enter an infinite loop, we see that the DriverManager is providing new instances of my connection as matches for the mysql URLs instead of the desired mysql driver/connection. FWIW, I have separately tested implementations that go straight to the mysql driver using this exact syntax (al beit only one at a time), and was able to successfully interact with each database individually from a test application outside of my driver.

    Read the article

  • How to pass operators as parameters

    - by Rodion Ingles
    I have to load an array of doubles from a file, multiply each element by a value in a table (different values for different elements), do some work on it, invert the multiplication (that is, divide) and then save the data back to file. Currently I implement the multiplication and division process in two separate methods. Now there is some extra work behind the scenes but apart from the specific statements where the multiplication/division occurs, the rest of the code is identical. As you can imagine, with this approach you have to be very careful making any changes. The surrounding code is not trivial, so its either a case of manually editing each method or copying changes from one method to the other and remembering to change the * and / operators. After too many close calls I am fed up of this and would like to make a common function which implements the common logic and two wrapper functions which pass which operator to use as a parameter. My initial approach was to use function pointers: MultiplyData(double data) { TransformData(data, &(operator *)); } DivideData(double data) { TransformData(data, &(operator /)); } TransformData(double data, double (*func)(double op1, double op2)) { /* Do stuff here... */ } However, I can't pass the operators as pointers (is this because it is an operator on a native type?), so I tried to use function objects. Initially I thought that multiplies and divides functors in <functional> would be ideal: MultiplyData(double data) { std::multiplies<double> multFunct; TransformData(data, &multFunct); } DivideData(double data) { std::divides<double> divFunct; TransformData(data, &divFunct); } TransformData(double data, std::binary_function<double, double, double> *funct) { /* Do stuff here... */ } As you can see I was trying to use a base class pointer to pass the functor polymorphically. The problem is that std::binary_function does not declare an operator() member for the child classes to implement. Is there something I am missing, or is the solution to implement my own functor heirarchy (which really seems more trouble than it is worth)?

    Read the article

  • Haskell data serialization of some data implementing a common type class

    - by Evan
    Let's start with the following data A = A String deriving Show data B = B String deriving Show class X a where spooge :: a -> Q [ Some implementations of X for A and B ] Now let's say we have custom implementations of show and read, named show' and read' respectively which utilize Show as a serialization mechanism. I want show' and read' to have types show' :: X a => a -> String read' :: X a => String -> a So I can do things like f :: String -> [Q] f d = map (\x -> spooge $ read' x) d Where data could have been [show' (A "foo"), show' (B "bar")] In summary, I wanna serialize stuff of various types which share a common typeclass so I can call their separate implementations on the deserialized stuff automatically. Now, I realize you could write some template haskell which would generate a wrapper type, like data XWrap = AWrap A | BWrap B deriving (Show) and serialize the wrapped type which would guarantee that the type info would be stored with it, and that we'd be able to get ourselves back at least an XWrap... but is there a better way using haskell ninja-ery? EDIT Okay I need to be more application specific. This is an API. Users will define their As, and Bs and fs as they see fit. I don't ever want them hacking through the rest of the code updating their XWraps, or switches or anything. The most i'm willing to compromise is one list somewhere of all the A, B, etc. in some format. Why? Here's the application. A is "Download a file from an FTP server." B is "convert from flac to mp3". A contains username, password, port, etc. information. B contains file path information. A and B are Xs, and Xs shall be called "Tickets." Q is IO (). Spooge is runTicket. I want to read the tickets off into their relevant data types and then write generic code that will runTicket on the stuff read' from the stuff on disk. At some point I have to jam type information into the serialized data.

    Read the article

  • Keeping floated divs inline

    - by Elliott
    I'm having trouble getting my layout working correctly, I have a main div and a sidebar div these are both float: left if the screen size is resized or if its viewed on screen smaller that what I have designed on (1920x1080) then the sidebar div drops below the main content. I tried placing a wrapper around each div, but this has no effect. <div id="header"> [Header] </div> <div id="content"> [Content] </div> <div id="sideBar"> [SideBar] </div> <div id="footer"> [Footer] </div> body { width: 100%; color: #000000; background-color: #000000; margin: 0; padding: 0; } #header { width: 100%; height: 110px; background-color: #336699; color: #FFFFFF; margin: 0px; padding: 0px; } #content { float: left; margin-left: 50px; width: 70%; height: 700px; margin-top: 40px; padding: 30px; background-color: #FFFFFF; margin-bottom: 40px; } #sideBar { float: left; margin-left: 50px; width: 15%; height: 400px; margin-top: 40px; padding: 30px; background-color: #FFFFFF; } #footer { width: 100%; height: 80px; background-color: #174555; margin: 0px; padding: 0px; color: #ffffff; clear: both; } Basicly both div's should resize until a certain size is reached, then scrolling should be enabled. I'm pretty sure I have done something simple wrong but i'm not much of a design person. Example can be shown here : Link Thanks for any advice :)

    Read the article

  • Do you use an exception class in your Perl programs? Why or why not?

    - by daotoad
    I've got a bunch of questions about how people use exceptions in Perl. I've included some background notes on exceptions, skip this if you want, but please take a moment to read the questions and respond to them. Thanks. Background on Perl Exceptions Perl has a very basic built-in exception system that provides a spring-board for more sophisticated usage. For example die "I ate a bug.\n"; throws an exception with a string assigned to $@. You can also throw an object, instead of a string: die BadBug->new('I ate a bug.'); You can even install a signal handler to catch the SIGDIE psuedo-signal. Here's a handler that rethrows exceptions as objects if they aren't already. $SIG{__DIE__} = sub { my $e = shift; $e = ExceptionObject->new( $e ) unless blessed $e; die $e; } This pattern is used in a number of CPAN modules. but perlvar says: Due to an implementation glitch, the $SIG{DIE} hook is called even inside an eval(). Do not use this to rewrite a pending exception in $@ , or as a bizarre substitute for overriding CORE::GLOBAL::die() . This strange action at a distance may be fixed in a future release so that $SIG{DIE} is only called if your program is about to exit, as was the original intent. Any other use is deprecated. So now I wonder if objectifying exceptions in sigdie is evil. The Questions Do you use exception objects? If so, which one and why? If not, why not? If you don't use exception objects, what would entice you to use them? If you do use exception objects, what do you hate about them, and what could be better? Is objectifying exceptions in the DIE handler a bad idea? Where should I objectify my exceptions? In my eval{} wrapper? In a sigdie handler? Are there any papers, articles or other resources on exceptions in general and in Perl that you find useful or enlightening.

    Read the article

  • python object to native c++ pointer

    - by Lodle
    Im toying around with the idea to use python as an embedded scripting language for a project im working on and have got most things working. However i cant seem to be able to convert a python extended object back into a native c++ pointer. So this is my class: class CGEGameModeBase { public: virtual void FunctionCall()=0; virtual const char* StringReturn()=0; }; class CGEPYGameMode : public CGEGameModeBase, public boost::python::wrapper<CGEPYGameMode> { public: virtual void FunctionCall() { if (override f = this->get_override("FunctionCall")) f(); } virtual const char* StringReturn() { if (override f = this->get_override("StringReturn")) return f(); return "FAILED TO CALL"; } }; Boost wrapping: BOOST_PYTHON_MODULE(GEGameMode) { class_<CGEGameModeBase, boost::noncopyable>("CGEGameModeBase", no_init); class_<CGEPYGameMode, bases<CGEGameModeBase> >("CGEPYGameMode", no_init) .def("FunctionCall", &CGEPYGameMode::FunctionCall) .def("StringReturn", &CGEPYGameMode::StringReturn); } and the python code: import GEGameMode def Ident(): return "Alpha" def NewGamePlay(): return "NewAlpha" def NewAlpha(): import GEGameMode import GEUtil class Alpha(GEGameMode.CGEPYGameMode): def __init__(self): print "Made new Alpha!" def FunctionCall(self): GEUtil.Msg("This is function test Alpha!") def StringReturn(self): return "This is return test Alpha!" return Alpha() Now i can call the first to functions fine by doing this: const char* ident = extract< const char* >( GetLocalDict()["Ident"]() ); const char* newgameplay = extract< const char* >( GetLocalDict()["NewGamePlay"]() ); printf("Loading Script: %s\n", ident); CGEPYGameMode* m_pGameMode = extract< CGEPYGameMode* >( GetLocalDict()[newgameplay]() ); However when i try and convert the Alpha class back to its base class (last line above) i get an boost error: TypeError: No registered converter was able to extract a C++ pointer to type class CGEPYGameMode from this Python object of type Alpha I have done alot of searching on the net but cant work out how to convert the Alpha object into its base class pointer. I could leave it as an object but rather have it as a pointer so some non python aware code can use it. Any ideas?

    Read the article

  • WinForm-style Invoke() in unmanaged C++

    - by Matt Green
    I've been playing with a DataBus-type design for a hobby project, and I ran into an issue. Back-end components need to notify the UI that something has happened. My implementation of the bus delivers the messages synchronously with respect to the sender. In other words, when you call Send(), the method blocks until all the handlers have called. (This allows callers to use stack memory management for event objects.) However, consider the case where an event handler updates the GUI in response to an event. If the handler is called, and the message sender lives on another thread, then the handler cannot update the GUI due to Win32's GUI elements having thread affinity. More dynamic platforms such as .NET allow you to handle this by calling a special Invoke() method to move the method call (and the arguments) to the UI thread. I'm guessing they use the .NET parking window or the like for these sorts of things. A morbid curiosity was born: can we do this in C++, even if we limit the scope of the problem? Can we make it nicer than existing solutions? I know Qt does something similar with the moveToThread() function. By nicer, I'll mention that I'm specifically trying to avoid code of the following form: if(! this->IsUIThread()) { Invoke(MainWindowPresenter::OnTracksAdded, e); return; } being at the top of every UI method. This dance was common in WinForms when dealing with this issue. I think this sort of concern should be isolated from the domain-specific code and a wrapper object made to deal with it. My implementation consists of: DeferredFunction - functor that stores the target method in a FastDelegate, and deep copies the single event argument. This is the object that is sent across thread boundaries. UIEventHandler - responsible for dispatching a single event from the bus. When the Execute() method is called, it checks the thread ID. If it does not match the UI thread ID (set at construction time), a DeferredFunction is allocated on the heap with the instance, method, and event argument. A pointer to it is sent to the UI thread via PostThreadMessage(). Finally, a hook function for the thread's message pump is used to call the DeferredFunction and de-allocate it. Alternatively, I can use a message loop filter, since my UI framework (WTL) supports them. Ultimately, is this a good idea? The whole message hooking thing makes me leery. The intent is certainly noble, but are there are any pitfalls I should know about? Or is there an easier way to do this?

    Read the article

  • No Method Error Undefined method 'save' for nil:NilClass

    - by BennyB
    I'm getting this error when i try to create a "Lecture" via my Lecture controller's create method. This used to work but i went on to work on other parts of the app & then of course i come back & something is now throwing this error when a user tries to create a Lecture in my app. I'm sure its something small i'm just overlooking (been at it a while & probably need to take a break)...but I'd appreciate if someone could let me know why this is happening...let me know if i need to post anything else...thx! The error I get NoMethodError in LecturesController#create undefined method `save' for nil:NilClass Rails.root: /Users/name/Sites/rails_projects/app_name Application Trace | Framework Trace | Full Trace app/controllers/lectures_controller.rb:13:in `create' My view to create a new Lecture views/lectures/new.html.erb <% provide(:title, 'Start a Lecture') %> <div class="container"> <div class="content-wrapper"> <h1>Create a Lecture</h1> <div class="row"> <div class="span 6 offset3"> <%= form_for(@lecture) do |f| %> <%= render 'shared/error_messages', :object => f.object %> <div class="field"> <%= f.text_field :title, :placeholder => "What will this Lecture be named?" %> <%= f.text_area :content, :placeholder => "Describe this Lecture & what will be learned..." %> </div> <%= f.submit "Create this Lecture", :class => "btn btn-large btn-primary" %> <% end %> </div> </div> </div> </div> Then my controller where its saying the error is coming from controllers/lectures_controller.rb class LecturesController < ApplicationController before_filter :signed_in_user, :only => [:create, :destroy] before_filter :correct_user, :only => :destroy def index end def new @lecture = current_user.lectures.build if signed_in? end def create if @lecture.save flash[:success] = "Lecture created!" redirect_to @lecture else @activity_items = [ ] render 'new' end end def show @lecture = Lecture.find(params[:id]) end def destroy @lecture.destroy redirect_to root_path end private def correct_user @lecture = current_user.lectures.find_by_id(params[:id]) redirect_to root_path if @lecture.nil? end

    Read the article

  • How can a C/C++ program put itself into background?

    - by Larry Gritz
    What's the best way for a running C or C++ program that's been launched from the command line to put itself into the background, equivalent to if the user had launched from the unix shell with '&' at the end of the command? (But the user didn't.) It's a GUI app and doesn't need any shell I/O, so there's no reason to tie up the shell after launch. But I want a shell command launch to be auto-backgrounded without the '&' (or on Windows). Ideally, I want a solution that would work on any of Linux, OS X, and Windows. (Or separate solutions that I can select with #ifdef.) It's ok to assume that this should be done right at the beginning of execution, as opposed to somewhere in the middle. One solution is to have the main program be a script that launches the real binary, carefully putting it into the background. But it seems unsatisfying to need these coupled shell/binary pairs. Another solution is to immediately launch another executed version (with 'system' or CreateProcess), with the same command line arguments, but putting the child in the background and then having the parent exit. But this seems clunky compared to the process putting itself into background. Edited after a few answers: Yes, a fork() (or system(), or CreateProcess on Windows) is one way to sort of do this, that I hinted at in my original question. But all of these solutions make a SECOND process that is backgrounded, and then terminate the original process. I was wondering if there was a way to put the EXISTING process into the background. One difference is that if the app was launched from a script that recorded its process id (perhaps for later killing or other purpose), the newly forked or created process will have a different id and so will not be controllable by any launching script, if you see what I'm getting at. Edit #2: fork() isn't a good solution for OS X, where the man page for 'fork' says that it's unsafe if certain frameworks or libraries are being used. I tried it, and my app complains loudly at runtime: "The process has forked and you cannot use this CoreFoundation functionality safely. You MUST exec()." I was intrigued by daemon(), but when I tried it on OS X, it gave the same error message, so I assume that it's just a fancy wrapper for fork() and has the same restrictions. Excuse the OS X centrism, it just happens to be the system in front of me at the moment. But I am indeed looking for a solution to all three platforms.

    Read the article

  • Copy image to BLOB from client pc aka Java function in Oracle

    - by mumich
    Hi guys, I've been stuck with this for past two days. I've go java function stored in Oracle system which is supposed to copy image from local drive do remote database and store it in BLOB - it's called CopyBLOB and looks like this: import java.sql.*; import oracle.sql.*; import java.io.*; public class CopyBLOB { static int id; static String fileName = null; static Connection conn = null; public CopyBLOB(int idz, String f) { id = idz; fileName = f; } public static void copy(int ident, String path) throws SQLException, FileNotFoundException { CopyBLOB cpB = new CopyBLOB(ident, path); cpB.getConnection(); cpB.callUpdate(id, fileName); } public void getConnection() throws SQLException { DriverManager.registerDriver (new oracle.jdbc.OracleDriver()); try { conn = DriverManager.getConnection("jdbc:oracle:thin:@oraserv.ms.mff.cuni.cz:1521:db", "xxx", "xxx"); } catch (SQLException sqlex) { System.out.println("SQLException while getting db connection: "+sqlex); if (conn != null) conn.close(); } catch (Exception ex) { System.out.println("Exception while getting db connection: "+ex); if (conn != null) conn.close(); } } public void callUpdate(int id, String file ) throws SQLException, FileNotFoundException { CallableStatement cs = null; try { conn.setAutoCommit(false); File f = new File(file); FileInputStream fin = new FileInputStream(f); cs = (CallableStatement) conn.prepareCall( "begin add_image(?,?); end;" ); cs.setInt(1, id ); cs.setBinaryStream(2, fin, (int) f.length()); cs.execute(); conn.setAutoCommit(true); } catch ( SQLException sqlex ) { System.out.println("SQLException in callUpdateUsingStream method of given status : " + sqlex.getMessage() ); } catch ( FileNotFoundException fnex ) { System.out.println("FileNotFoundException in callUpdateUsingStream method of given status : " + fnex.getMessage() ); } finally { try { if (cs != null) cs.close(); if (conn != null) conn.close(); } catch ( Exception ex ) { System.out.println("Some exception in callUpdateUsingStream method of given status : " + ex.getMessage( ) ); } } } } The wrapper function is defined in package "MyPackage" as folows: procedure image_adder( id varchar2, path varchar2 ) AS language java name 'CopyBLOB.copy(java.lang.String, java.lang.String)'; And the inserting function called image_add is as simple as this: procedure add_image( id numeric(10), pic blob) AS BEGIN insert into pictures values (seq_pic.nextval, id, pic); END add_image; Now the problem: When I type call MyPackage.image_adder(1, 'd:\samples\img.jpg'); I get the ORA-29531 Error: No method copy in class CopyBLOB. Can you help me, please?

    Read the article

  • Can't figure out the color of an svg element

    - by yass
    I have a very simple HTML page, viewable on gh-pages with the following 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" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <link href="style.css" media="screen" rel="stylesheet" type="text/css"> <script src='http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js'> </script> </head> <body> <div id="page"> <div id="content"> <div id="heatmap"> <svg style="margin-left: 80px; color: rgb(255, 255, 255);" width="800" height="880"> <g transform="translate(80,80)"> <rect style="color: rgb(255, 255, 255);" height="720" width="720"> </rect> </g> </svg> </div> </div> </div> </body> </html> with the following CSS: body { background-color: #FFFFFF; font-family: Arial, Helvetica, sans-serif; font-size: 14px; color: #FFFFFF; } #wrapper { margin: 0 auto; padding: 0; } #page { width: 1000px; margin: 0 auto; padding: 40px 0px 0px 0px; } #content { float: left; width: 660px; padding: 0px 0px 0px 0px; background: #FFFFFF; } I expect the rectangle, 'svg rect' to be the color #FFFFFF, or white. But it shows up as some other color. I opened it up in firebug, and it shows the computed color to be #FFFFF:

    Read the article

  • Using jQuery to store basic text string in mySQL base?

    - by Kenny Bones
    Could someone point me in the right direction here? Basically, I've got this jQuery code snippet: $('.bggallery_images').click(function () { var newBG = "url('" + $(this).attr('src'); var fullpath = $(this).attr('src'); var filename = fullpath.replace('img/Bakgrunner/', ''); $('#wrapper').css('background-image', newBG); // Lagre til SQL $.ajax({ url: "save_to_db.php", // The url to your function to handle saving to the db data: filename, dataType: 'Text', type: 'POST', // Could also use GET if you prefer success: function (data) { // Just for testing purposes. alert('Background changed to: ' + data); } }); }); This is being run when I click a certain button. So it's actually within a click handler. If I understand this correctly, this snippet takes the source if the image I just clicked and strips it so I end up with only the filename. If I do an alert(filename), I get the filename only. So this is working ok. But then, it does an ajax call to a php file called "save_to_db.php" and sends data: filename. This is correct right? Then, it does a callback which does an alert + data. Does this seem correct so far? Cause my php file looks like this: <?php require("dbconnect2.php"); $uploadstring = $_POST['filename']; $sessionid = $_SESSION['id']; echo ($sessionid); mysql_query("UPDATE brukere SET brukerBakgrunn = '$uploadstring' WHERE brukerID=" .$_SESSION['id']); mysql_close(); ?> When I click the image, the jQuery snippet fires and I get the results of this php file as output for the alert box. I think that the variables somehow are empty. Because notice the echo($sessionid); which is a variable I've created just to test what the session ID is. And it returns nothing. What could be the issue here? Edit: I just tried to echo out the $uploadstring variable as well and it also returns nothing. It's like the jQuery snippet doesn't even pass the variable on to the php file?

    Read the article

  • Directly Jump to another C++ function

    - by maligree
    I'm porting a small academic OS from TriCore to ARM Cortex (Thumb-2 instruction set). For the scheduler to work, I sometimes need to JUMP directly to another function without modifying the stack nor the link register. On TriCore (or, rather, on tricore-g++), this wrapper template (for any three-argument-function) works: template< class A1, class A2, class A3 > inline void __attribute__((always_inline)) JUMP3( void (*func)( A1, A2, A3), A1 a1, A2 a2, A3 a3 ) { typedef void (* __attribute__((interrupt_handler)) Jump3)( A1, A2, A3); ( (Jump3)func )( a1, a2, a3 ); } //example for using the template: JUMP3( superDispatch, this, me, next ); This would generate the assembler instruction J (a.k.a. JUMP) instead of CALL, leaving the stack and CSAs unchanged when jumping to the (otherwise normal) C++ function superDispatch(SchedulerImplementation* obj, Task::Id from, Task::Id to). Now I need an equivalent behaviour on ARM Cortex (or, rather, for arm-none-linux-gnueabi-g++), i.e. generate a B (a.k.a. BRANCH) instruction instead of BLX (a.k.a. BRANCH with link and exchange). But there is no interrupt_handler attribute for arm-g++ and I could not find any equivalent attribute. So I tried to resort to asm volatile and writing the asm code directly: template< class A1, class A2, class A3 > inline void __attribute__((always_inline)) JUMP3( void (*func)( A1, A2, A3), A1 a1, A2 a2, A3 a3 ) { asm volatile ( "mov.w r0, %1;" "mov.w r1, %2;" "mov.w r2, %3;" "b %0;" : : "r"(func), "r"(a1), "r"(a2), "r"(a3) : "r0", "r1", "r2" ); } So far, so good, in my theory, at least. Thumb-2 requires function arguments to be passed in the registers, i.e. r0..r2 in this case, so it should work. But then the linker dies with undefined reference to `r6' on the closing bracket of the asm statement ... and I don't know what to make of it. OK, I'm not the expert in C++, and the asm syntax is not very straightforward... so has anybody got a hint for me? A hint to the correct __attribute__ for arm-g++ would be one way, a hint to fix the asm code would be another. Another way maybe would be to tell the compiler that a1..a3 should already be in the registers r0..r2 when the asm statement is entered (I looked into that a bit, but did not find any hint).

    Read the article

  • Unusual RJS error

    - by rrb
    Hi, I am getting the following error in my RoR application: RJS error: TypeError: element is null Element.update("notice", "Comment Posted"); Element.update("allcomments", "\n\n\n \n\n waht now?\n\n \n\n \n\n \n\n asdfasdfa\n \n\n \n\n asdfasdf\n \n\n\n\n\n"); But when I hit the refresh button, I can see my partial updated. Here's my code: show_comments View: <table> <% comments.each do |my_comment| %> <tr> <td><%=h my_comment.comment%></td> </tr> <% end %> </table> show View: <div class="wrapper"> <div class="rescale"> <div class="img-main"> <%= image_tag @deal.photo.url %> </div> </div> <div class="description"> <p class ="description_content"> <%=h @deal.description %> </p> </div> </div> <p> <b>Category:</b> <%=h @deal.category %> </p> <p> <b>Base price:</b> <%=h @deal.base_price %> </p> <%#*<p>%> <%#*<b>Discount:</b>%> <%#=h @deal.discount %> <%#*</p>%> <%= link_to 'Edit', edit_deal_path(@deal) %> | <%= link_to 'Back', deals_path %> <p> <%= render :partial=>'deal_comments', :locals=>{ :comments=>Comment.new(:deal_id=>@deal.id)} %> </p> <div id="allcomments"> <%= render :partial=>'show_comments', :locals=>{ :comments=>Comment.find(@deal.comments)} %> </div> Controller: def create @comment = Comment.new(params[:comment]) render :update do |page| if @comment.save page.replace_html 'notice', 'Comment Posted' else page.replace_html 'notice', 'Something went wrong' end page.replace_html 'allcomments', :partial=> 'deals/show_comments', :locals=>{:comments=> @comment.deal.comments} end end def show_comments @deal = Deal.find(params[:deal_id]) render :partial=> "deals/show_comments", :locals=>{:comments=>@deal.comments} end end

    Read the article

  • Is it OK to put a standard, pure C header #include directive inside a namespace?

    - by mic_e
    I've got a project with a class log in the global namespace (::log). So, naturally, after #include <cmath>, the compiler gives an error message each time I try to instantiate an object of my log class, because <cmath> pollutes the global namespace with lots of three-letter methods, one of them being the logarithm function log(). So there are three possible solutions, each having their unique ugly side-effects. Move the log class to it's own namespace and always access it with it's fully qualified name. I really want to avoid this because the logger should be as convenient as possible to use. Write a mathwrapper.cpp file which is the only file in the project that includes <cmath>, and makes all the required <cmath> functions available through wrappers in a namespace math. I don't want to use this approach because I have to write a wrapper for every single required math function, and it would add additional call penalty (cancelled out partially by the -flto compiler flag) The solution I'm currently considering: Replace #include <cmath> by namespace math { #include "math.h" } and then calculating the logarithm function via math::log(). I have tried it out and it does, indeed, compile, link and run as expected. It does, however, have multiple downsides: It's (obviously) impossible to use <cmath>, because the <cmath> code accesses the functions by their fully qualified names, and it's deprecated to use in C++. I've got a really, really bad feeling about it, like I'm gonna get attacked and eaten alive by raptors. So my question is: Is there any recommendation/convention/etc that forbid putting include directives in namespaces? Could anything go wrong with diferent C standard library implementations (I use glibc), different compilers (I use g++ 4.7, -std=c++11), linking? Have you ever tried doing this? Are there any alternate ways to banish the math functions from the global namespace? I've found several similar questions on stackoverflow, but most were about including other C++ headers, which obviously is a bad idea, and those that weren't made contradictory statements about linking behaviour for C libraries. Also, would it be beneficial to additionally put the #include <math.h> inside extern "C" {}?

    Read the article

< Previous Page | 70 71 72 73 74 75 76 77 78 79 80 81  | Next Page >