Search Results

Search found 51 results on 3 pages for 'mixin'.

Page 2/3 | < Previous Page | 1 2 3  | Next Page >

  • What are the elegant ways to do MixIns in Python?

    - by Slava Vishnyakov
    I need to find an elegant way to do 2 kinds of MixIns. First: class A(object): def method1(self): do_something() Now, a MixInClass should make method1 do this: do_other() - A.method1() - do_smth_else() - i.e. basically "wrap" the older function. I'm pretty sure there must exist a good solution to this. Second: class B(object): def method1(self): do_something() do_more() In this case, I want MixInClass2 to be able to inject itself between do_something() and do_more(), i.e.: do_something() - MixIn.method1 - do_more(). I understand that probably this would require modifying class B - that's ok, just looking for simplest ways to achieve this. These are pretty trivial problems and I actually solved them, but my solution is tainted. Fisrt one by using self._old_method1 = self.method1(); self.method1() = self._new_method1(); and writing _new_method1() that calls to _old_method1(). Problem: multiple MixIns will all rename to _old_method1 and it is inelegant. Second MixIn one was solved by creating a dummy method call_mixin(self): pass and injecting it between calls and defining self.call_mixin(). Again inelegant and will break on multiple MixIns.. Any ideas?

    Read the article

  • Handling multiple media queries in Sass with Twitter Bootstrap

    - by Keith
    I have a Sass mixin for my media queries based on Twitter Bootstrap's responsive media queries: @mixin respond-to($media) { @if $media == handhelds { /* Landscape phones and down */ @media (max-width: 480px) { @content; } } @else if $media == small { /* Landscape phone to portrait tablet */ @media (max-width: 767px) {@content; } } @else if $media == medium { /* Portrait tablet to landscape and desktop */ @media (min-width: 768px) and (max-width: 979px) { @content; } } @else if $media == large { /* Large desktop */ @media (min-width: 1200px) { @content; } } @else { @media only screen and (max-width: #{$media}px) { @content; } } } And I call them throughout my SCSS file like so: .link { color:blue; @include respond-to(medium) { color: red; } } However, sometimes I want to style multiple queries with the same styles. Right now I'm doing them like this: .link { color:blue; /* this is fine for handheld and small sizes*/ /*now I want to change the styles that are cascading to medium and large*/ @include respond-to(medium) { color: red; } @include respond-to(large) { color: red; } } but I'm repeating code so I'm wondering if there is a more concise way to write it so I can target multiple queries. Something like this so I don't need to repeat my code (I know this doesn't work): @include respond-to(medium, large) { color: red; } Any suggestions on the best way to handle this?

    Read the article

  • Is there a case for parameterising using Abstract classes rather than Interfaces?

    - by Chris
    I'm currently developing a component based API that is heavily stateful. The top level components implement around a dozen interfaces each. The stock top-level components therefore sit ontop of a stack of Abstract implementations which in turn contain multiple mixin implementations and implement multiple mixin interfaces. So far, so good (I hope). The problem is that the base functionality is extremely complex to implement (1,000s of lines in 5 layers of base classes) and therefore I do not wish for component writers to implement the interfaces themselves but rather to extend my base classes (where all the boiler plate code is already written). If the API therefore accepts interfaces rather than references to the Abstract implementation that I wish for component writers to extends, then I have a risk that the implementer will not perform the validation that is both required and assumed by other areas of code. Therefore, my question is, is it sometimes valid to paramerise API methods using an abstract implementation reference rather than a reference to the interface(s) that it implements? Do you have an example of a well-designed API that uses this technique or am I trying to talk myself into bad-practice?

    Read the article

  • Who could ask for more with LESS CSS? (Part 1 of 3&ndash;Features)

    - by ToStringTheory
    It wasn’t very long ago that I first began to get into CSS precompilers such as SASS (Syntactically Awesome Stylesheets) and LESS (The Dynamic Stylesheet Language) and I had been hooked on the idea since.  When I finally had a new project come up, I leapt at the opportunity to try out one of these languages. Introduction To be honest, I was hesitant at first to add either framework as I didn’t really know much more than what I had read on their homepages, and I didn’t like the idea of adding too much complexity to a project - I couldn’t guarantee I would be the only person to support it in the future. Thankfully, both of these languages just add things into CSS.  You don’t HAVE to know LESS or SASS to do anything, you can still do your old school CSS, and your output will be the same.  However, when you want to start doing more advanced things such as variables, mixins, and color functions, the functionality is all there for you to utilize. From what I had read, SASS has a few more features than LESS, which is why I initially tried to figure out how to incorporate it into a MVC 4 project. However, through my research, I couldn’t find a way to accomplish this without including some bit of the Ruby on Rails framework on the computer running it, and I hated the fact that I had to do that.  Besides SASS, there is little chance of me getting into the RoR framework, at least in the next couple years.  So in the end, I settled with using LESS. Features So, what can LESS (or SASS) do for you?  There are several reasons I have come to love it in the past few weeks. 1 – Constants Using LESS, you can finally declare a constant and use its value across an entire CSS file. The case that most people would be familiar with is colors.  Wanting to declare one or two color variables that comprise the theme of the site, and not have to retype out their specific hex code each time, but rather a variable name.  What’s great about this is that if you end up having to change it, you only have to change it in one place.  An important thing to note is that you aren’t limited to creating constants just for colors, but for strings and measurements as well. 2 – Inheritance This is a cool feature in my mind for simplicity and organization.  Both LESS and SASS allow you to place selectors within other selectors, and when it is compiled, the languages will break the rules out as necessary and keep the inheritance chain you created in the selectors. Example LESS Code: #header {   h1 {     font-size: 26px;     font-weight: bold;   }   p {     font-size: 12px;     a     {       text-decoration: none;       &:hover {         border-width: 1px       }     }   } } Example Compiled CSS: #header h1 {   font-size: 26px;   font-weight: bold; } #header p {   font-size: 12px; } #header p a {   text-decoration: none; } #header p a:hover {   border-width: 1px; } 3 - Mixins Mixins are where languages like this really shine.  The ability to mixin other definitions setup a parametric mixin.  There is really a lot of content in this area, so I would suggest looking at http://lesscss.org for more information.  One of the things I would suggest if you do begin to use LESS is to also grab the mixins.less file from the Twitter Bootstrap project.  This file already has a bunch of predefined mixins for things like border-radius with all of the browser specific prefixes.  This alone is of great use! 4 – Color Functions This is the last thing I wanted to point out as my final post in this series will be utilizing these functions in a more drawn out manner.  Both LESS and SASS provide functions for getting information from a color (R,G,B,H,S,L).  Using these, it is easy to define a primary color, and then darken or lighten it a little for your needs.  Example: Example LESS Code: @base-color: #111; @red:        #842210; #footer {   color: (@base-color + #003300);   border-left:  2px;   border-right: 2px;   border-color: desaturate(@red, 10%); } Example Compiled CSS: #footer {    color: #114411;    border-left:  2px;    border-right: 2px;    border-color: #7d2717; } I have found that these can be very useful and powerful when constructing a site theme. Conclusion I came across LESS and SASS when looking for the best way to implement some type of CSS variables for colors, because I hated having to do a Find and Replace in all of the files using the colors, and in some instances, you couldn’t just find/replace because of the color choices interfering with other colors (color to replace of #000, yet come colors existed like #0002bc).  So in many cases I would end up having to do a Find and manually check each one. In my next post, I am going to cover how I’ve come to set up these items and the structure for the items in the project, as well as the conventions that I have come to start using.  In the final post in the series, I will cover a neat little side project I built in LESS dealing with colors!

    Read the article

  • Identifying methods with a specified Id in D [migrated]

    - by Ekyo777
    I want to have specific methods with a specific pattern recognized at compile time and registered along with a specified id trough mixins in a parent class. ex.: take a method 'X' from a class with a predetermined id:5, what I want is that, in a mixin in a parent class, method X will be registered as a delegate with its id to be called later on by its id. What would be the best way to specify the Id considering I want the id to be of type int and only the specified methods to be registered? should I (if it is even possible) do it with a custom annotation pretty much like the @property but with an argument, like: @autoregister(id) void method(...) if it is possible to do it this way, an example or a link to the documentation on how to do it would be nice since I didn't find it in the documentation.

    Read the article

  • Ruby is already using the class name of my model

    - by Octopus Inc
    I'm making a forum application with various levels of authorization, one of which is a Monitor. I am doing this by extending my User class, and I plan on fine tuning this with "-ship" classes (e.g. administratorship, authorship, moderatorship, etc.). Apparently the Monitor class is part of ruby mixin. How do I keep my resource name without the collisions?

    Read the article

  • DRY way of calling a method in every rails model

    - by Tim
    Along the same lines as this question, I want to call acts_as_reportable inside every model so I can do one-off manual reports in the console in my dev environment (with a dump of the production data). What's the best way to do this? Putting acts_as_reportable if ENV['RAILS_ENV'] == "development" in every model is getting tedious and isn't very DRY at all. Everyone says monkey patching is the devil, but a mixin seems overkill. Thanks!

    Read the article

  • why am i getting StackOverflowError?

    - by IttayD
    In groovyConsole I have this: import groovy.util.* import org.codehaus.groovy.runtime.* def gse = new GroovyScriptEngine("c:\\temp") def script = gse.loadScriptByName("say.groovy") this.metaClass.mixin script say("bye") say.groovy contains def say(String msg) { println(msg) }

    Read the article

  • Chef-solo cannot locate an nginx recipe template

    - by crftr
    I have been recently experimenting with Chef. I thought I would attempt to rebuild my personal web server using chef-solo. It's an AWS instance running the Amazon 64bit Linux AMI. My first objective is to install nginx. I have cloned the Opscode cookbook repository, and am using their nginx cookbook. My problem appears to be that chef-solo cannot find a template after it has started the process. The command I'm using is chef-solo -j /etc/chef/dna.json dna.json { "nginx": { "user": "ec2-user" }, "recipes": [ "nginx" ] } solo.rb file_cache_path "/var/chef-solo" cookbook_path "/var/chef-solo/cookbooks" ...the output [root@ip-10-202-221-135 chef-solo]# chef-solo -j /etc/chef/dna.json /usr/lib64/ruby/gems/1.9.1/gems/systemu-2.2.0/lib/systemu.rb:29: Use RbConfig instead of obsolete and deprecated Config. [Fri, 27 Jan 2012 19:41:36 +0000] INFO: *** Chef 0.10.8 *** [Fri, 27 Jan 2012 19:41:37 +0000] INFO: Setting the run_list to ["nginx"] from JSON [Fri, 27 Jan 2012 19:41:37 +0000] INFO: Run List is [recipe[nginx]] [Fri, 27 Jan 2012 19:41:37 +0000] INFO: Run List expands to [nginx] [Fri, 27 Jan 2012 19:41:37 +0000] INFO: Starting Chef Run for ip-10-202-221-135.ec2.internal [Fri, 27 Jan 2012 19:41:37 +0000] INFO: Running start handlers [Fri, 27 Jan 2012 19:41:37 +0000] INFO: Start handlers complete. [Fri, 27 Jan 2012 19:41:37 +0000] INFO: Missing gem 'mysql' [Fri, 27 Jan 2012 19:41:38 +0000] INFO: Processing package[nginx] action install (nginx::default line 21) [Fri, 27 Jan 2012 19:41:39 +0000] INFO: Processing directory[/var/log/nginx] action create (nginx::default line 23) [Fri, 27 Jan 2012 19:41:39 +0000] INFO: Processing template[/usr/sbin/nxensite] action create (nginx::default line 30) [Fri, 27 Jan 2012 19:41:39 +0000] INFO: Processing template[/usr/sbin/nxdissite] action create (nginx::default line 30) [Fri, 27 Jan 2012 19:41:39 +0000] INFO: Processing template[nginx.conf] action create (nginx::default line 38) [Fri, 27 Jan 2012 19:41:39 +0000] INFO: Processing template[/etc/nginx/sites-available/default] action create (nginx::default line 46) [Fri, 27 Jan 2012 19:41:39 +0000] INFO: template[/etc/nginx/sites-available/default] mode changed to 644 [Fri, 27 Jan 2012 19:41:39 +0000] ERROR: template[/etc/nginx/sites-available/default] (nginx::default line 46) has had an error [Fri, 27 Jan 2012 19:41:39 +0000] ERROR: template[/etc/nginx/sites-available/default] (/var/chef-solo/cookbooks/nginx/recipes/default.rb:46:in `from_file') had an error: template[/etc/nginx/sites-available/default] (nginx::default line 46) had an error: Errno::ENOENT: No such file or directory - (/tmp/chef-rendered-template20120127-29441-1yp55vz, /etc/nginx/sites-available/default) /usr/lib64/ruby/1.9.1/fileutils.rb:519:in `rename' /usr/lib64/ruby/1.9.1/fileutils.rb:519:in `block in mv' /usr/lib64/ruby/1.9.1/fileutils.rb:1515:in `block in fu_each_src_dest' /usr/lib64/ruby/1.9.1/fileutils.rb:1531:in `fu_each_src_dest0' /usr/lib64/ruby/1.9.1/fileutils.rb:1513:in `fu_each_src_dest' /usr/lib64/ruby/1.9.1/fileutils.rb:508:in `mv' /usr/lib64/ruby/gems/1.9.1/gems/chef-0.10.8/lib/chef/provider/template.rb:47:in `block in action_create' /usr/lib64/ruby/gems/1.9.1/gems/chef-0.10.8/lib/chef/mixin/template.rb:48:in `block in render_template' /usr/lib64/ruby/1.9.1/tempfile.rb:316:in `open' /usr/lib64/ruby/gems/1.9.1/gems/chef-0.10.8/lib/chef/mixin/template.rb:45:in `render_template' /usr/lib64/ruby/gems/1.9.1/gems/chef-0.10.8/lib/chef/provider/template.rb:99:in `render_with_context' /usr/lib64/ruby/gems/1.9.1/gems/chef-0.10.8/lib/chef/provider/template.rb:39:in `action_create' /usr/lib64/ruby/gems/1.9.1/gems/chef-0.10.8/lib/chef/resource.rb:440:in `run_action' /usr/lib64/ruby/gems/1.9.1/gems/chef-0.10.8/lib/chef/runner.rb:45:in `run_action' /usr/lib64/ruby/gems/1.9.1/gems/chef-0.10.8/lib/chef/runner.rb:81:in `block (2 levels) in converge' /usr/lib64/ruby/gems/1.9.1/gems/chef-0.10.8/lib/chef/runner.rb:81:in `each' /usr/lib64/ruby/gems/1.9.1/gems/chef-0.10.8/lib/chef/runner.rb:81:in `block in converge' /usr/lib64/ruby/gems/1.9.1/gems/chef-0.10.8/lib/chef/resource_collection.rb:94:in `block in execute_each_resource' /usr/lib64/ruby/gems/1.9.1/gems/chef-0.10.8/lib/chef/resource_collection/stepable_iterator.rb:116:in `call' /usr/lib64/ruby/gems/1.9.1/gems/chef-0.10.8/lib/chef/resource_collection/stepable_iterator.rb:116:in `call_iterator_block' /usr/lib64/ruby/gems/1.9.1/gems/chef-0.10.8/lib/chef/resource_collection/stepable_iterator.rb:85:in `step' /usr/lib64/ruby/gems/1.9.1/gems/chef-0.10.8/lib/chef/resource_collection/stepable_iterator.rb:104:in `iterate' /usr/lib64/ruby/gems/1.9.1/gems/chef-0.10.8/lib/chef/resource_collection/stepable_iterator.rb:55:in `each_with_index' /usr/lib64/ruby/gems/1.9.1/gems/chef-0.10.8/lib/chef/resource_collection.rb:92:in `execute_each_resource' /usr/lib64/ruby/gems/1.9.1/gems/chef-0.10.8/lib/chef/runner.rb:76:in `converge' /usr/lib64/ruby/gems/1.9.1/gems/chef-0.10.8/lib/chef/client.rb:312:in `converge' /usr/lib64/ruby/gems/1.9.1/gems/chef-0.10.8/lib/chef/client.rb:160:in `run' /usr/lib64/ruby/gems/1.9.1/gems/chef-0.10.8/lib/chef/application/solo.rb:192:in `block in run_application' /usr/lib64/ruby/gems/1.9.1/gems/chef-0.10.8/lib/chef/application/solo.rb:183:in `loop' /usr/lib64/ruby/gems/1.9.1/gems/chef-0.10.8/lib/chef/application/solo.rb:183:in `run_application' /usr/lib64/ruby/gems/1.9.1/gems/chef-0.10.8/lib/chef/application.rb:67:in `run' /usr/lib64/ruby/gems/1.9.1/gems/chef-0.10.8/bin/chef-solo:25:in `<top (required)>' /usr/bin/chef-solo:19:in `load' /usr/bin/chef-solo:19:in `<main>' [Fri, 27 Jan 2012 19:41:39 +0000] ERROR: Running exception handlers [Fri, 27 Jan 2012 19:41:39 +0000] ERROR: Exception handlers complete [Fri, 27 Jan 2012 19:41:39 +0000] FATAL: Stacktrace dumped to /var/chef-solo/chef-stacktrace.out [Fri, 27 Jan 2012 19:41:39 +0000] FATAL: Errno::ENOENT: template[/etc/nginx/sites-available/default] (nginx::default line 46) had an error: Errno::ENOENT: No such file or directory - (/tmp/chef-rendered-template20120127-29441-1yp55vz, /etc/nginx/sites-available/default) What am I doing incorrectly?

    Read the article

  • CSS optimization - extra classes in dom or preprocessor-repetitive styling in css file?

    - by anna.mi
    I'm starting on a fairly large project and I'm considering the option of using LESS for pre-processing my css. the useful thing about LESS is that you can define a mixin that contains for example: .border-radius(@radius) { -webkit-border-radius: @radius; -moz-border-radius: @radius; -o-border-radius: @radius; -ms-border-radius: @radius; border-radius: @radius; } and then use it in a class declaration as .rounded-div { .border-radius(10px); } to get the outputted css as: .rounded-div { -webkit-border-radius: 10px; -moz-border-radius: 10px; -o-border-radius: 10px; -ms-border-radius: 10px; border-radius: 10px; } this is extremely useful in the case of browser prefixes. However this same concept could be used to encapsulate commonly-used css, for example: .column-container { overflow: hidden; display: block; width: 100%; } .column(@width) { float: left; width: @width; } and then use this mixin whenever i need columns in my design: .my-column-outer { .column-container(); background: red; } .my-column-inner { .column(50%); font-color: yellow; } (of course, using the preprocessor we could easily expand this to be much more useful, eg. pass the number of columns and the container width as variables and have LESS determine the width of each column depending on the number of columns and container width!) the problem with this is that when compliled, my final css file would have 100 such declarations, copy&pasted, making the file huge and bloated and repetitive. The alternative to this would be to use a grid system which has predefined classes for each column-layout option, eg .c-50 ( with a "float: left; width:50%;" definition ), .c-33, .c-25 to accomodate for a 2-column, 3-column and 4-column layout and then use these classes to my dom. i really mislike the idea of the extra classes, from experience it results to bloated dom (creating extra divs just to attach the grid classes to). Also the most basic tutorial for html/css would tell you that the dom should be separated from the styling - grid classes are styling related! to me, its the same as attaching a "border-radius-10" class to the .rounded-div example above! on the other hand, the large css file that would result from the repetitive code is also a disadvantage so i guess my question is, which one would you recommend? and which do you use? and, which solution is best for optimization? apart from the larger file size, has there even been any research on whether browser renders multiple classes faster than a large css file, or the other way round? tnx! i'd love to hear your opinion!

    Read the article

  • how to dynamically add observer methods to an Ember.js object

    - by Rick Moss
    So i am trying to dynamically add these observer methods to a Ember.js object holderStandoutCheckedChanged: (-> if @get("controller.parent.isLoaded") @get("controller").toggleParentStandout(@get("standoutHolderChecked")) ).observes("standoutHolderChecked") holderPaddingCheckedChanged: (-> if @get("controller.parent.isLoaded") @get("controller").toggleParentPadding(@get("holderPaddingChecked")) ).observes("holderPaddingChecked") holderMarginCheckedChanged: (-> if @get("controller.parent.isLoaded") @get("controller").toggleParentMargin(@get("holderMarginChecked")) ).observes("holderMarginChecked") I have this code so far but the item.methodToCall function is not getting called methodsToDefine = [ {checkerName: "standoutHolderChecked", methodToCall: "toggleParentStandout"}, {checkerName: "holderPaddingChecked", methodToCall: "toggleParentPadding"}, {checkerName: "holderMarginChecked", methodToCall: "toggleParentMargin"} ] add_this = { } for item in methodsToDefine add_this["#{item.checkerName}Changed"] = (-> if @get("controller.parent.isLoaded") @get("controller")[item.methodToCall](@get(item.checkerName)) ).observes(item.checkerName) App.ColumnSetupView.reopen add_this Can anyone tell me what i am doing wrong ? Is there a better way to do this ? Should i be doing this in a mixin ? If so please

    Read the article

  • How can I quote strings in SASS?

    - by Stavros Korokithakis
    I'm using SASS to generate a @font-face mixin, however this: =remotefont(!name, !url) @font-face font-family = !name src = url(!url + ".eot") src = local(!name), url(!url + ".ttf") format("truetype") +remotefont("My font", "/myfont.ttf") becomes this: @font-face { font-family: My font; src: url(/myfont.ttf.eot); src: local(My font), url(/myfont.ttf.ttf) format(truetype); } No matter how much I try, I can't have it quote either "My font" (with "!name") or "truetype" (it removes the quotes). Any ideas on how I can do this?

    Read the article

  • What is the correct usage of blueprint-typography-body([$font-size])?

    - by Alexis Abril
    Recent convert to RoR and I've been using Compass w/ Blueprint to dip into the proverbial pool. Compass has been fantastic, but I've come across something strange within the Typography library. The blueprint-typography-body mixin contains the following: =blueprint-typography-body($font-size: $blueprint-font-size) line-height: 1.5 +normal-text font-size: 100% * $font-size / 16px My question revolves around "font-size." I'm a bit lost, as I would expect to pass in a font size and have that size reflected upon page load. However, in this scenario the formula seems to dictate a percentage against the default font. ie: +blueprint-typography-body(10px) //produces 7.5px off of the default font size of 12px from what I can tell. In essence, I'm curious if there is a standard to setting font size within Compass other than explicitly declaring "font-size: 10px". Note: The reason I'm leaning towards Blueprint/Compass font stylings is due to the standardization of line-heights, fonts and colors.

    Read the article

  • When to use a module, and when to use a class

    - by Matt Briggs
    I am currently working through the Gregory Brown Ruby Best Practices book. Early on, he is talking about refactoring some functionality from helper methods on a related class, to some methods on module, then had the module extend self. Hadn't seen that before, after a quick google, found out that extend self on a module lets methods defined on the module see each other, which makes sense. Now, my question is when would you do something like this module StyleParser extend self def process(text) ... end def style_tag?(text) ... end end and then refer to it in tests with @parser = Prawn::Document::Text::StyleParser as opposed to just using a class with some class methods on it? is it so that you can use it as a mixin? or are there other reasons I'm not seeing?

    Read the article

  • logging in scala

    - by IttayD
    In Java, the standard idiom for logging is to create a static variable for a logger object and use that in the various methods. In Scala, it looks like the idiom is to create a Logging trait with a logger member and mixin the trait in concrete classes. This means that each time an object is created it calls the logging framework to get a logger and also the object is bigger due to the additional reference. Is there an alternative that allows the ease of use of "with Logging" while still using a per-class logger instance? EDIT: My question is not about how one can write a logging framework in Scala, but rather how to use an existing one (log4j) without incurring an overhead of performance (getting a reference for each instance) or code complexity. Also, yes, I want to use log4j, simply because I'll use 3rd party libraries written in Java that are likely to use log4j.

    Read the article

  • Scope of Constants in Ruby Modules

    - by user204078
    I'm having a little problem with constant scope in mixin modules. Let's say I have something like this module Auth USER_KEY = "user" unless defined? USER_KEY def authorize user_id = session[USER_KEY] def end The USER_KEY constant should default to "user" unless it's already defined. Now I might mix this into a couple of places, but in one of those places the USER_KEY needs to be different, so we might have something like this class ApplicationController < ActionController::Base USER_KEY = "my_user" include Auth def test_auth authorize end end I would expect that USER_KEY would be "my_user" when used in authorize, since it's already defined, but it's still "user", taken from the modules definition of USER_KEY. Anyone have any idea how to get authorize to use the classes version of USER_KEY?

    Read the article

  • Node.js Lockstep Multiplayer Architecture

    - by Wakaka
    Background I'm using the lockstep model for a multiplayer Node.js/Socket.IO game in a client-server architecture. User input (mouse or keypress) is parsed into commands like 'attack' and 'move' on the client, which are sent to the server and scheduled to be executed on a certain tick. This is in contrast to sending state data to clients, which I don't wish to use due to bandwidth issues. Each tick, the server will send the list of commands on that tick (possibly empty) to each client. The server and all clients will then process the commands and simulate that tick in exactly the same way. With Node.js this is actually quite simple due to possibility of code sharing between server and client. I'll just put the deterministic simulator in the /shared folder which can be run by both server and client. The server simulation is required so that there is an authoritative version of the simulation which clients cannot alter. Problem Now, the game has many entity classes, like Unit, Item, Tree etc. Entities are created in the simulator. However, for each class, it has some methods that are shared and some that are client-specific. For instance, the Unit class has addHp method which is shared. It also has methods like getSprite (gets the image of the entity), isVisible (checks if unit can be seen by the client), onDeathInClient (does a bunch of stuff when it dies only on the client like adding announcements) and isMyUnit (quick function to check if the client owns the unit). Up till now, I have been piling all the client functions into the shared Unit class, and adding a this.game.isServer() check when necessary. For instance, when the unit dies, it will call if (!this.game.isServer()) { this.onDeathInClient(); }. This approach has worked pretty fine so far, in terms of functionality. But as the codebase grew bigger, this style of coding seems a little strange. Firstly, the client code is clearly not shared, and yet is placed under the /shared folder. Secondly, client-specific variables for each entity are also instantiated on the server entity (like unit.sprite) and can run into problems when the server cannot instantiate the variable (it doesn't have Image class like on browsers). So my question is, is there a better way to organize the client code, or is this a common way of doing things for lockstep multiplayer games? I can think of a possible workaround, but it does have its own problems. Possible workaround (with problems) I could use Javascript mixins that are only added when in a browser. Thus, in the /shared/unit.js file in the /shared folder, I would have this code at the end: if (typeof exports !== 'undefined') module.exports = Unit; else mixin(Unit, LocalUnit); Then I would have /client/localunit.js store an object LocalUnit of client-side methods for Unit. Now, I already have a publish-subscribe system in place for events in the simulator. To remove the this.game.isServer() checks, I could publish entity-specific events whenever I want the client to do something. For instance, I would do this.publish('Death') in /shared/unit.js and do this.subscribe('Death', this.onDeathInClient) in /client/localunit.js. But this would make the simulator's event listeners list on the server and the client different. Now if I want to clear all subscribed events only from the shared simulator, I can't. Of course, it is possible to create two event subscription systems - one client-specific and one shared - but now the publish() method would have to do if (!this.game.isServer()) { this.publishOnClient(event); }. All in all, the workaround off the top of my head seems pretty complicated for something as simple as separating the client and shared code. Thus, I wonder if there is an established and simpler method for better code organization, hopefully specific to Node.js games.

    Read the article

  • CSS compilers and converting IE hacks to conditional css

    - by xckpd7
    Skip to bottom for question, but first, a little context. So I have been looking into CSS compilers (like Sass & Less) for a while, and have been really interested in them, not because they help me understand anything easier (I've been doing css for a couple of years now) but rather they cut down on cruft and help me see things easier. I recently have been looking into reliably implementing inline-block (and clearfix), which require lots of extraneous code & hacks. Now according to all the authorities in the field, I shouldn't put IE hacks in the same page I do my CSS in, I should make them conditional. But for me that is a really big hassle to go through and manage all this additional code, which is why I really like things like Less. Instead of applying unsemantic classes, you specify a mixin and apply it once, and you're all set. So I guess I got a little of the track (I wanted to explain my points) but bascially, I'm at the point where these CSS compilers are very useful for me, and allow me to abstract a lot of the cruft away, and reliably apply them once and then just compile it. I would like to have a way to be able to compile IE specific styles into their own conditional files (ala Less / Sass) so I don't have to deal with managing 2 files for no reason. Does anything like a script/applcation that runs and can make underscore / star hacks apart of their own file exist?

    Read the article

  • Why would I need a using statement to Libary B extn methods, if they're used in Library A & it's Li

    - by Greg
    Hi, I have: Main Program Class - uses Library A Library A - has partial classes which mix in methods from Library B Library B - mix in methods & interfaces Why would I need a using statement to LibaryB just to get their extension methods working in the main class? That is given that it's Library B that defines the classes that will be extended. EDIT - Except from code // *** PROGRAM *** using TopologyDAL; using Topology; // *** THIS WAS NEEDED TO GET EXTN METHODS APPEARING *** class Program { static void Main(string[] args) { var context = new Model1Container(); Node myNode; // ** trying to get myNode mixin methods to appear seems to need using line to point to Library B *** } } // ** LIBRARY A namespace TopologyDAL { public partial class Node { // Auto generated from EF } public partial class Node : INode<int> // to add extension methods from Library B { public int Key } } // ** LIBRARY B namespace ToplogyLibrary { public static class NodeExtns { public static void FromNodeMixin<T>(this INode<T> node) { // XXXX } } public interface INode<T> { // Properties T Key { get; } // Methods } }

    Read the article

  • multiple models in Rails with a shared interface

    - by dfondente
    I'm not sure of the best structure for a particular situation in Rails. We have several types of workshops. The administration of the workshops is the same regardless of workshop type, so the data for the workshops is in a single model. We collect feedback from participants about the workshops, and the questionnaire is different for each type of workshop. I want to access the feedback about the workshop from the workshop model, but the class of the associated model will depend on the type of workshop. If I was doing this in something other than Rails, I would set up an abstract class for WorkshopFeedback, and then have subclasses for each type of workshop: WorkshopFeedbackOne, WorkshopFeedbackTwo, WorkshopFeedbackThree. I'm unsure how to best handle this with Rails. I currently have: class Workshop < ActiveRecord::Base has_many :workshop_feedbacks end class Feedback < ActiveRecord::Base belongs_to :workshop has_many :feedback_ones has_many :feedback_twos has_many :feedback_threes end class FeedbackOne < ActiveRecord::Base belongs_to :feedback end class FeedbackTwo < ActiveRecord::Base belongs_to :feedback end class FeedbackThree < ActiveRecord::Base belongs_to :feedback end This doesn't seem like to the cleanest way to access the feedback from the workshop model, as accessing the correct feedback will require logic investigating the Workshop type and then choosing, for instance, @workshop.feedback.feedback_one. Is there a better way to handle this situation? Would it be better to use a polymorphic association for feedback? Or maybe using a Module or Mixin for the shared Feedback interface? Note: I am avoiding using Single Table Inheritance here because the FeedbackOne, FeedbackTwo, FeedbackThree models do not share much common data, so I would end up with a large sparsely populated table with STI.

    Read the article

  • Mixing policy-based design with CRTP in C++

    - by Eitan
    I'm attempting to write a policy-based host class (i.e., a class that inherits from its template class), with a twist, where the policy class is also templated by the host class, so that it can access its types. One example where this might be useful is where a policy (used like a mixin, really), augments the host class with a polymorphic clone() method. Here's a minimal example of what I'm trying to do: template <template <class> class P> struct Host : public P<Host<P> > { typedef P<Host<P> > Base; typedef Host* HostPtr; Host(const Base& p) : Base(p) {} }; template <class H> struct Policy { typedef typename H::HostPtr Hptr; Hptr clone() const { return Hptr(new H((Hptr)this)); } }; Policy<Host<Policy> > p; Host<Policy> h(p); int main() { return 0; } This, unfortunately, fails to compile, in what seems to me like circular type dependency: try.cpp: In instantiation of ‘Host<Policy>’: try.cpp:10: instantiated from ‘Policy<Host<Policy> >’ try.cpp:16: instantiated from here try.cpp:2: error: invalid use of incomplete type ‘struct Policy<Host<Policy> >’ try.cpp:9: error: declaration of ‘struct Policy<Host<Policy> >’ try.cpp: In constructor ‘Host<P>::Host(const P<Host<P> >&) [with P = Policy]’: try.cpp:17: instantiated from here try.cpp:5: error: type ‘Policy<Host<Policy> >’ is not a direct base of ‘Host<Policy>’ If anyone can spot an obvious mistake, or has successfuly mixing CRTP in policies, I would appreciate any help.

    Read the article

  • Rail test case fixtures not loading

    - by Deano
    Rails appears to not be loading any fixtures for unit or functional tests. I have a simple 'products.yml' that parses and appears correct: ruby: title: Programming Ruby 1.9 description: Ruby is the fastest growing and most exciting dynamic language out there. If you need to get working programs delivered fast, you should add Ruby to your toolbox. price: 49.50 image_url: ruby.png My controller functional test begins with: require 'test_helper' class ProductsControllerTest < ActionController::TestCase fixtures :products setup do @product = products(:one) @update = { :title => 'Lorem Ipsum' , :description => 'Wibbles are fun!' , :image_url => 'lorem.jpg' , :price => 19.95 } end According to the book, Rails should "magically" load the fixtures (as my test_helper.rb has fixtures :all in it. I also added the explicit fixtures load (seen above). Yes Rails complains: user @ host ~/Dropbox/Rails/depot > rake test:functionals (in /Somewhere/Users/user/Dropbox/Rails/depot) /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby -Ilib:test "/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb" "test/functional/products_controller_test.rb" Loaded suite /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader Started EEEEEEE Finished in 0.062506 seconds. 1) Error: test_should_create_product(ProductsControllerTest): NoMethodError: undefined method `products' for ProductsControllerTest:Class /test/functional/products_controller_test.rb:7 2) Error: test_should_destroy_product(ProductsControllerTest): NoMethodError: undefined method `products' for ProductsControllerTest:Class /test/functional/products_controller_test.rb:7 ... I did come across the other Rails test fixture question http://stackoverflow.com/questions/1547634/rails-unit-testing-doesnt-load-fixtures, but that leads to a plugin issue (something to do with the order of loading fixtures). BTW, I am developing on Mac OS X 10.6 with Rail 2.3.5 and Ruby 1.8.7, no additional plugins (beyond the base install). Any pointers on how to debug, why the magic of Rails appears to be failing here? Is it a version problem? Can I trace code into the libraries and find the answer? There are so many "mixin" modules I can't find where the fixtures method really lives.

    Read the article

  • What to Expect in Rails 4

    - by mikhailov
    Rails 4 is nearly there, we should be ready before it released. Most developers are trying hard to keep their application on the edge. Must see resources: 1) @sikachu talk: What to Expect in Rails 4.0 - YouTube 2) Rails Guides release notes: http://edgeguides.rubyonrails.org/4_0_release_notes.html There is a mix of all major changes down here: ActionMailer changes excerpt: Asynchronously send messages via the Rails Raise an ActionView::MissingTemplate exception when no implicit template could be found ActionPack changes excerpt Added controller-level etag additions that will be part of the action etag computation Add automatic template digests to all CacheHelper#cache calls (originally spiked in the cache_digests plugin) Add Routing Concerns to declare common routes that can be reused inside others resources and routes Added ActionController::Live. Mix it in to your controller and you can stream data to the client live truncate now always returns an escaped HTML-safe string. The option :escape can be used as false to not escape the result Added ActionDispatch::SSL middleware that when included force all the requests to be under HTTPS protocol ActiveModel changes excerpt AM::Validation#validates ability to pass custom exception to :strict option Changed `AM::Serializers::JSON.include_root_in_json' default value to false. Now, AM Serializers and AR objects have the same default behaviour Added ActiveModel::Model, a mixin to make Ruby objects work with AP out of box Trim down Active Model API by removing valid? and errors.full_messages ActiveRecord changes excerpt Use native mysqldump command instead of structure_dump method when dumping the database structure to a sql file. Attribute predicate methods, such as article.title?, will now raise ActiveModel::MissingAttributeError if the attribute being queried for truthiness was not read from the database, instead of just returning false ActiveRecord::SessionStore has been extracted from Active Record as activerecord-session_store gem. Please read the README.md file on the gem for the usage Fix reset_counters when there are multiple belongs_to association with the same foreign key and one of them have a counter cache Raise ArgumentError if list of attributes to change is empty in update_all Add Relation#load. This method explicitly loads the records and then returns self Deprecated most of the 'dynamic finder' methods. All dynamic methods except for find_by_... and find_by_...! are deprecated Added ability to ActiveRecord::Relation#from to accept other ActiveRecord::Relation objects Remove IdentityMap ActiveSupport changes excerpt ERB::Util.html_escape now escapes single quotes ActiveSupport::Callbacks: deprecate monkey patch of object callbacks Replace deprecated memcache-client gem with dalli in ActiveSupport::Cache::MemCacheStore Object#try will now return nil instead of raise a NoMethodError if the receiving object does not implement the method, but you can still get the old behavior by using the new Object#try! Object#try can't call private methods Add ActiveSupport::Deprecations.behavior = :silence to completely ignore Rails runtime deprecations What are the most important changes for you?

    Read the article

  • C++ invalid reference problem

    - by Karol
    Hi all, I'm writing some callback implementation in C++. I have an abstract callback class, let's say: /** Abstract callback class. */ class callback { public: /** Executes the callback. */ void call() { do_call(); }; protected: /** Callback call implementation specific to derived callback. */ virtual void do_call() = 0; }; Each callback I create (accepting single-argument functions, double-argument functions...) is created as a mixin using one of the following: /** Makes the callback a single-argument callback. */ template <typename T> class singleArgumentCallback { protected: /** Callback argument. */ T arg; public: /** Constructor. */ singleArgumentCallback(T arg): arg(arg) { } }; /** Makes the callback a double-argument callback. */ template <typename T, typename V> class doubleArgumentCallback { protected: /** Callback argument 1. */ T arg1; /** Callback argument 2. */ V arg2; public: /** Constructor. */ doubleArgumentCallback(T arg1, V arg2): arg1(arg1), arg2(arg2) { } }; For example, a single-arg function callback would look like this: /** Single-arg callbacks. */ template <typename T> class singleArgFunctionCallback: public callback, protected singleArgumentCallback<T> { /** Callback. */ void (*callbackMethod)(T arg); public: /** Constructor. */ singleArgFunctionCallback(void (*callback)(T), T argument): singleArgumentCallback<T>(argument), callbackMethod(callback) { } protected: void do_call() { this->callbackMethod(this->arg); } }; For user convenience, I'd like to have a method that creates a callback without having the user think about details, so that one can call (this interface is not subject to change, unfortunately): void test3(float x) { std::cout << x << std::endl; } void test5(const std::string& s) { std::cout << s << std::endl; } make_callback(&test3, 12.0f)->call(); make_callback(&test5, "oh hai!")->call(); My current implementation of make_callback(...) is as follows: /** Creates a callback object. */ template <typename T, typename U> callback* make_callback( void (*callbackMethod)(T), U argument) { return new singleArgFunctionCallback<T>(callbackMethod, argument); } Unfortunately, when I call make_callback(&test5, "oh hai!")->call(); I get an empty string on the standard output. I believe the problem is that the reference gets out of scope after callback initialization. I tried using pointers and references, but it's impossible to have a pointer/reference to reference, so I failed. The only solution I had was to forbid substituting reference type as T (for example, T cannot be std::string&) but that's a sad solution since I have to create another singleArgCallbackAcceptingReference class accepting a function pointer with following signature: void (*callbackMethod)(T& arg); thus, my code gets duplicated 2^n times, where n is the number of arguments of a callback function. Does anybody know any workaround or has any idea how to fix it? Thanks in advance!

    Read the article

  • My Dijit DateTimeCombo widget doesn't send selected value on form submission

    - by david bessire
    i need to create a Dojo widget that lets users specify date & time. i found a sample implementation attached to an entry in the Dojo bug tracker. It looks nice and mostly works, but when i submit the form, the value sent by the client is not the user-selected value but the value sent from the server. What changes do i need to make to get the widget to submit the date & time value? Sample usage is to render a JSP with basic HTML tags (form & input), then dojo.addOnLoad a function which selects the basic elements by ID, adds dojoType attribute, and dojo.parser.parse()-es the page. Thanks in advance. The widget is implemented in two files. The application uses Dojo 1.3. File 1: DateTimeCombo.js dojo.provide("dojox.form.DateTimeCombo"); dojo.require("dojox.form._DateTimeCombo"); dojo.require("dijit.form._DateTimeTextBox"); dojo.declare( "dojox.form.DateTimeCombo", dijit.form._DateTimeTextBox, { baseClass: "dojoxformDateTimeCombo dijitTextBox", popupClass: "dojox.form._DateTimeCombo", pickerPostOpen: "pickerPostOpen_fn", _selector: 'date', constructor: function (argv) {}, postMixInProperties: function() { dojo.mixin(this.constraints, { /* datePattern: 'MM/dd/yyyy HH:mm:ss', timePattern: 'HH:mm:ss', */ datePattern: 'MM/dd/yyyy HH:mm', timePattern: 'HH:mm', clickableIncrement:'T00:15:00', visibleIncrement:'T00:15:00', visibleRange:'T01:00:00' }); this.inherited(arguments); }, _open: function () { this.inherited(arguments); if (this._picker!==null && (this.pickerPostOpen!==null && this.pickerPostOpen!=="")) { if (this._picker.pickerPostOpen_fn!==null) { this._picker.pickerPostOpen_fn(this); } } } } ); File 2: _DateTimeCombo.js dojo.provide("dojox.form._DateTimeCombo"); dojo.require("dojo.date.stamp"); dojo.require("dijit._Widget"); dojo.require("dijit._Templated"); dojo.require("dijit._Calendar"); dojo.require("dijit.form.TimeTextBox"); dojo.require("dijit.form.Button"); dojo.declare("dojox.form._DateTimeCombo", [dijit._Widget, dijit._Templated], { // invoked only if time picker is empty defaultTime: function () { var res= new Date(); res.setHours(0,0,0); return res; }, // id of this table below is the same as this.id templateString: " <table class=\"dojoxDateTimeCombo\" waiRole=\"presentation\">\ <tr class=\"dojoxTDComboCalendarContainer\">\ <td>\ <center><input dojoAttachPoint=\"calendar\" dojoType=\"dijit._Calendar\"></input></center>\ </td>\ </tr>\ <tr class=\"dojoxTDComboTimeTextBoxContainer\">\ <td>\ <center><input dojoAttachPoint=\"timePicker\" dojoType=\"dijit.form.TimeTextBox\"></input></center>\ </td>\ </tr>\ <tr><td><center><button dojoAttachPoint=\"ctButton\" dojoType=\"dijit.form.Button\">Ok</button></center></td></tr>\ </table>\ ", widgetsInTemplate: true, constructor: function(arg) {}, postMixInProperties: function() { this.inherited(arguments); }, postCreate: function() { this.inherited(arguments); this.connect(this.ctButton, "onClick", "_onValueSelected"); }, // initialize pickers to calendar value pickerPostOpen_fn: function (parent_inst) { var parent_value = parent_inst.attr('value'); if (parent_value !== null) { this.setValue(parent_value); } }, // expects a valid date object setValue: function(value) { if (value!==null) { this.calendar.attr('value', value); this.timePicker.attr('value', value); } }, // return a Date constructed date in calendar & time in time picker. getValue: function() { var value = this.calendar.attr('value'); var result=value; if (this.timePicker.value !== null) { if ((this.timePicker.value instanceof Date) === true) { result.setHours(this.timePicker.value.getHours(), this.timePicker.value.getMinutes(), this.timePicker.value.getSeconds()); return result; } } else { var defTime=this.defaultTime(); result.setHours(defTime.getHours(), defTime.getMinutes(), defTime.getSeconds()); return result; } }, _onValueSelected: function() { var value = this.getValue(); this.onValueSelected(value); }, onValueSelected: function(value) {} });

    Read the article

< Previous Page | 1 2 3  | Next Page >