Search Results

Search found 3148 results on 126 pages for 'angularjs scope'.

Page 21/126 | < Previous Page | 17 18 19 20 21 22 23 24 25 26 27 28  | Next Page >

  • Reason for unintuitive UnboundLocalError behaviour 2

    - by Jonathan
    Following up on Reason for unintuitive UnboundLocalError behaviour (I will assume you've read it). Consider the following Python script: def f(): # a+=1 # 1 aa=a aa+=1 # b+='b' # 2 bb=b bb+='b' c[0]+='c' # 3 c.append('c') cc=c cc.append('c') # 4 a=1 b='b' c=['c'] f() print a print b print c The result of the script is: 1 b ['cc', 'c', 'c'] The commented out lines (marked 1,2) are lines that would through an UnboundLocalError and the SO question I referenced explains why. However, the line marked 3 works! By default, lists are copied by reference in Python, therefore it's understandable that c changes when cc changes. But why should Python allow c to change in the first place, if it didn't allow changes to a and b directly from the method's scope? I don't see how the fact that by default lists are copied by reference in Python should make this design decision inconsistent. What am I missing folks?

    Read the article

  • Include only the latest/newest associated record with active record?

    - by railsnewbie
    is it possible to load only the latest associated record of an associated table? an example: class author attr_accessible :first_name, :last_name, :birthday has_many :books end class book attr_accessible :pages, :date of publication, :title belongs_to :author end Is there a way to generate a scope to load only the newest released book the author wrote? Or the book with the most pages? I know, that I could include or join all books. But I don't know if its possible to load only a specific book for each author. So that I could do a query like this: Author.authors_and_their_newest_book So that I could get these results first_name_author_1, last_name_author_1, birthday_author_1, pages_book_3, date of publication_book_3, title_book_3 first_name_author_2, last_name_author_2, birthday_author_2, pages_book_5, date of publication_book_5, title_book_5 first_name_author_3, last_name_author_3, birthday_author_3, pages_book_9, date of publication_book_9, title_book_9 ...

    Read the article

  • Access property from include inside a class method in PHP

    - by Jojo
    How do you make a class property available to the other included file inside the same class' method? // file A.php class A { private $var = 1; public function go() { include('another.php'); } } in another file: // this is another.php file // how can I access class A->var? echo $var; // this can't be right Is this possible given the scope. If var is an array then we can use extract but if var is not, we can wrap it in an array. Is there a better way? Thanks!

    Read the article

  • Using named_scopes on the join model of a has_many :through

    - by uberllama
    Hi folks. I've been beating my head against the wall on something that on the surface should be very simple. Lets say I have the following simplified models: user.rb has_many :memberships has_many :groups, :through => :memberships membership.rb belongs_to :group belongs_to :user STATUS_CODES = {:admin => 1, :member => 2, :invited => 3} named_scope :active, :conditions => {:status => [[STATUS_CODES[:admin], STATUS_CODES[:member]]} group.rb has_many :memberships has_many :users, :through => :memberships Simple, right? So what I want to do is get a collection of all the groups a user is active in, using the existing named scope on the join model. Something along the lines of User.find(1).groups.active. Obviously this doesn't work. But as it stands, I need to do something like User.find(1).membrships.active.all(:include => :group) which returns a collection of memberships plus groups. I don't want that. I know I can add another has_many on the User model with conditions that duplicate the :active named_scope on the Membership model, but that's gross. has_many :active_groups, :through => :memberships, :source => :group, :conditions => ... So my question: is there a way of using intermediary named scopes when traversing directly between models? Many thanks.

    Read the article

  • About function scopes in javascript

    - by Shawn
    Look at the code below. I want to alert the value of i at the moment that specific listener was added. Is other words, clicking each marker should alert a different value. Where can I store the value of i in a way that it won't change and be accessible inside the scope of that function? Here is problematic code: (it is difficult to test because you need a key from Google) <html> <head> <title>a</title> <script type="text/javascript"> function init() { map = new GMap2(document.getElementById("map_canvas")); // http://code.google.com/intl/es/apis/maps/documentation/reference.html#GMap2 map.setCenter(new GLatLng(0, 0), 1); // http://code.google.com/intl/es/apis/maps/documentation/reference.html#GMap2.setCenter for(var i = 0; i < 10; i++) { var marker = new GMarker(point); // http://code.google.com/intl/es/apis/maps/documentation/reference.html#GMarker map.addOverlay(marker); // http://code.google.com/intl/es/apis/maps/documentation/reference.html#GMap2.addOverlay GEvent.addListener(marker, "click", function() // http://code.google.com/intl/es/apis/maps/documentation/reference.html#GEvent.addListener { alert(i); // Problem: I want the value of i at the moment when the listener is added. }); } } window.onload = init; </script> </head> <body id="map_canvas"> </body> </html> Thanks!

    Read the article

  • How to: Searchlogic and Tags

    - by bob
    I have installed searchlogic and added will_paginate etc. I currently have a product model that has tagging enabled using the acts_as_taggable_on plugin. I want to search the tags using searchlogic. Here is the taggable plugin page: http://github.com/mbleigh/acts-as-taggable-on Each product has a "tag_list" that i can access using Product.tag_list or i can access a specific tag using Product.tags[0] I can't find the scope to use for searching however with search logic. Here is my part of my working form. <p> <%= f.label :name_or_description_like, "Name" %><br /> <%= f.text_field :name_or_description_like %> </p> I have tried :name_or_description_or_tagged_with_like and :name_or_description_or_tags_like and also :name_or_description_or_tags_list_like to try and get it to work but I keep have an error that says the options i have tried are not found (named scopes not found). I am wondering how I can get this working or how to create my own named_scope that would allow me to search the tags added to each product by the taggable plugin. Thanks!

    Read the article

  • Spring bean's DESTROY-METHOD attribute and web-application "prototype"d bean

    - by EugeneP
    Can get work the attribute "destroy-method". First, even if I type non-existing method name into "destroy-method" attribute, Spring initialization completes fine (already strange!). Next, when a bean has a "prototype" scope, then I suppose it must be destroyed before the application is closed. That not happens, it is simply never called in my case. Though, after extracting this bean I can call this method explicitly and it does its job. Could you explain why this method is never called in my Spring 2.5 case? p.s. The method exists, it is public and has no arguments. It seems to be a more difficult task then I thought. The problem is that this destroy method is called whenever the context is closed, and this is a rare case. My question is this: I have a web app. I have a "prototype"-scoped bean. What I need is when the current session is closed, this destroy method was automatically called by Spring. I can do it by hand, but is there any solution how to make Spring do this job? It destroys the bean after the session is destroyed, it might be possible for Spring to call a method on that bean before destroying it?

    Read the article

  • How to access method variables from within an anonymous function in JavaScript?

    - by Hussain
    I'm writing a small ajax class for personal use. In the class, I have a "post" method for sending post requests. The post method has a callback parameter. In the onreadystatechange propperty, I need to call the callback method. Something like this: this.requestObject.onreadystatechange = function() { callback(this.responseText); } However, I can't access the callback variable from within the anonomous function. How can I bring the callback variable into the scope of the onreadystatechange anonomous function? edit: Here's the full code so far: function request() { this.initialize = function(errorHandeler) { try { try { this.requestObject = new XDomainRequest(); } catch(e) { try { this.requestObject = new XMLHttpRequest(); } catch (e) { try { this.requestObject = new ActiveXObject("Msxml2.XMLHTTP"); //newer versions of IE5+ } catch (e) { this.requestObject = new ActiveXObject("Microsoft.XMLHTTP"); //older versions of IE5+ } } } } catch(e) { errorHandeler(); } } this.post = function(url,data) { var response;var escapedData = ""; if (typeof data == 'object') { for (i in data) { escapedData += escape(i)+'='+escape(data[i])+'&'; } escapedData = escapedData.substr(0,escapedData.length-1); } else { escapedData = escape(data); } this.requestObject.open('post',url,true); this.requestObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); this.requestObject.setRequestHeader("Content-length", data.length); this.requestObject.setRequestHeader("Connection", "close"); this.requestObject.onreadystatechange = function() { if (this.readyState == 4) { // call callback function } } this.requestObject.send(data); }

    Read the article

  • named_scope + average is causing the table to be specified more then once in the sql query run on po

    - by hadees
    I have a named scopes like so... named_scope :gender, lambda { |gender| { :joins => {:survey_session => :profile }, :conditions => { :survey_sessions => { :profiles => { :gender => gender } } } } } and when I call it everything works fine. I also have this average method I call... Answer.average(:rating, :include => {:survey_session => :profile}, :group => "profiles.career") which also works fine if I call it like that. However if I were to call it like so... Answer.gender('m').average(:rating, :include => {:survey_session => :profile}, :group => "profiles.career") I get... ActiveRecord::StatementInvalid: PGError: ERROR: table name "profiles" specified more than once : SELECT avg("answers".rating) AS avg_rating, profiles.career AS profiles_career FROM "answers" LEFT OUTER JOIN "survey_sessions" survey_sessions_answers ON "survey_sessions_answers".id = "answers".survey_session_id LEFT OUTER JOIN "profiles" ON "profiles".id = "survey_sessions_answers".profile_id INNER JOIN "survey_sessions" ON "survey_sessions".id = "answers".survey_session_id INNER JOIN "profiles" ON "profiles".id = "survey_sessions".profile_id WHERE ("profiles"."gender" = E'm') GROUP BY profiles.career Which is a little hard to read but says I'm including the table profiles twice. If I were to just remove the include from average it works but it isn't really practical because average is actually being called inside a method which gets passed the scoped. So there is some times gender or average might get called with out each other and if either was missing the profile include it wouldn't work. So either I need to know how to fix this apparent bug in Rails or figure out a way to know what scopes were applied to a ActiveRecord::NamedScope::Scope object so that I could check to see if they have been applied and if not add the include for average.

    Read the article

  • Design: How to declare a specialized memory handler class

    - by Michael Dorgan
    On an embedded type system, I have created a Small Object Allocator that piggy backs on top of a standard memory allocation system. This allocator is a Boost::simple_segregated_storage< class and it does exactly what I need - O(1) alloc/dealloc time on small objects at the cost of a touch of internal fragmentation. My question is how best to declare it. Right now, it's scope static declared in our mem code module, which is probably fine, but it feels a bit exposed there and is also now linked to that module forever. Normally, I declare it as a monostate or a singleton, but this uses the dynamic memory allocator (where this is located.) Furthermore, our dynamic memory allocator is being initialized and used before static object initialization occurs on our system (as again, the memory manager is pretty much the most fundamental component of an engine.) To get around this catch 22, I added an extra 'if the small memory allocator exists' to see if the small object allocator exists yet. That if that now must be run on every small object allocation. In the scheme of things, this is nearly negligable, but it still bothers me. So the question is, is there a better way to declare this portion of the memory manager that helps decouple it from the memory module and perhaps not costing that extra isinitialized() if statement? If this method uses dynamic memory, please explain how to get around lack of initialization of the small object portion of the manager.

    Read the article

  • Associative Array / Object can't be read in functions

    - by Matrym
    At the very beginning of the javascript file, I have: var lbp = {}; lbp.defaults = { minLength: 40 }; I can successfully alert it afterwards, with: alert(lbp.defaults.minLength); But as soon as I put it inside a function, when I alert, I get "Undefined". What gives, and how do I avoid this? Is it absolutely necessary to pass this variable into each function, for example, by doing: function(lbp) { alert(lbp.defaults.minLength); } I would have thought that defining it first, it would attain global scope and not be required to be passed in? Thanks in advance for enlightening me :) ==================================== EDIT: The problem seems like it might be my initialize function is itself defined within lbp. Is there any way to use this function var, and still use lbp vars inside it? lbp.initialize = function() { alert(lbp.defaults.minLength); }; The full bit of code looks like this: <script type="text/javascript"> var lbp = { defaults: { minLength: 40 } }; lbp.initialize = function() { alert(lbp.defaults.minLength); }; window.onload = lbp.initialize; </script>

    Read the article

  • Emulating Test::More::done_testing - what is the most idiomatic way?

    - by DVK
    I have to build unit tests for in environment with a very old version of Test::More (perl5.8 with $Test::More::VERSION being '0.80') which predates the addition of done_testing(). Upgrading to newer Test::More is out of the question for practical reasons. And I am trying to avoid using no_tests - it's generally a bad idea not catching when your unit test dies prematurely. What is the most idiomatic way of running a configurable amount of tests, assuming no no_tests or done_testing() is used? Details: My unit tests usually take the form of: use Test::More; my @test_set = ( [ "Test #1", $param1, $param2, ... ] ,[ "Test #1", $param1, $param2, ... ] # ,... ); foreach my $test (@test_set) { run_test($test); } sub run_test { # $expected_tests += count_tests($test); ok(test1($test)) || diag("Test1 failed"); # ... } The standard approach of use Test::More tests => 23; or BEGIN {plan tests => 23} does not work since both are obviously executed before @tests is known. My current approach involves making @tests global and defining it in the BEGIN {} block as follows: use Test::More; BEGIN { our @test_set = (); # Same set of tests as above my $expected_tests = 0; foreach my $test (@tests) { my $expected_tests += count_tests($test); } plan tests = $expected_tests; } our @test_set; # Must do!!! Since first "our" was in BEGIN's scope :( foreach my $test (@test_set) { run_test($test); } # Same sub run_test {} # Same I feel this can be done more idiomatically but not certain how to improve. Chief among the smells is the duplicate our @test_test declarations - in BEGIN{} and after it.

    Read the article

  • Change a finder method w/ parameters to an association

    - by Sai Emrys
    How do I turn this into a has_one association? (Possibly has_one + a named scope for size.) class User < ActiveRecord::Base has_many :assets, :foreign_key => 'creator_id' def avatar_asset size = :thumb # The LIKE is because it might be a .jpg, .png, or .gif. # More efficient methods that can handle that are OK. ;) self.assets.find :first, :conditions => ["thumbnail = '#{size}' and filename LIKE ?", self.login + "_#{size}.%"] end end EDIT: Cuing from AnalogHole on Freenode #rubyonrails, we can do this: has_many :assets, :foreign_key => 'creator_id' do def avatar size = :thumb find :first, :conditions => ["thumbnail = ? and filename LIKE ?", size.to_s, proxy_owner.login + "_#{size}.%"] end end ... which is fairly cool, and makes syntax a bit better at least. However, this still doesn't behave as well as I would like. Particularly, it doesn't allow for further nice find chaining (such that it doesn't execute this find until it's gotten all its conditions). More importantly, it doesn't allow for use in an :include. Ideally I want to do something like this: PostsController def show post = Post.get_cache(params[:id]) { Post.find(params[:id], :include => {:comments => {:users => {:avatar_asset => :thumb}} } ... end ... so that I can cache the assets together with the post. Or cache them at all, really - e.g. get_cache(user_id){User.find(user_id, :include => :avatar_assets)} would be a good first pass. This doesn't actually work (self == User), but is correct in spirit: has_many :avatar_assets, :foreign_key => 'creator_id', :class_name => 'Asset', :conditions => ["filename LIKE ?", self.login + "_%"] (Also posted on Refactor My Code.)

    Read the article

  • Limiting a search to records from last_request_at...

    - by bgadoci
    I am trying to figure out how to display a count for records that have been created in a table since the last_request_at of a user. In my view I am counting the notes of a question with the following code: <% unless @questions.empty? %> <% @questions.each do |question| %> <%= h(question.notes.count) %> end end This is happening in the /views/users/show.html.erb file. Instead of counting all the notes for the question, I would only like to count the notes that have been created since the users last_request_at datetime. I don't neccessarily want to scope notes to display this 'new notes' count application wide, just simply in this one instance. To accomplish I am assuming I need to create a variable in the User#show action and call it in the view but not really sure how to do that. Other information you may need: class Note < ActiveRecord::Base belongs_to :user belongs_to :question end class Question < ActiveRecord::Base has_many :notes, :dependent => :destroy belongs_to :user end

    Read the article

  • Which of the following Java coding fragments is better?

    - by Simon
    This isn't meant to be subjective, I am looking for reasons based on resource utilisation, compiler performance, GC performance etc. rather than elegance. Oh, and the position of brackets doesn't count, so no stylistic comments please. Take the following loop; Integer total = new Integer(0); Integer i; for (String str : string_list) { i = Integer.parse(str); total += i; } versus... Integer total = 0; for (String str : string_list) { Integer i = Integer.parse(str); total += i; } In the first one i is function scoped whereas in the second it is scoped in the loop. I have always thought (believed) that the first one would be more efficient because it just references an existing variable already allocated on the stack, whereas the second one would be pushing and popping i each iteration of the loop. There are quite a lot of other cases where I tend to scope variables more broadly than perhaps necessary so I thought I would ask here to clear up a gap in my knowledge. Also notice that assignment of the variable on initialisation either involving the new operator or not. Do any of these sorts of semi-stylistic semi-optimisations make any difference at all?

    Read the article

  • Variable Scoping in a method and its persistence in C++

    - by de costo
    Consider the following public method that adds an integer variable to a vector of ints(private member) in a class in C++. KoolMethod() { int x; x = 10; KoolList.Add(x); } Vector<int>KoolList; But is this a valid addition to a vector ??? Upon calling the method, it creates a local variable. The scope of this local variable ends the moment the execution control leaves the method. And since this local variable is allocated on a stack(on the method call), any member of KoolList points to an invalid memory location in deallocated stack which may or may not contain the expected value of x. Is this an accurate description of above mechanism ?? Is there a need for creating an int in heap storage using "new" operator everytime a value needs to be added to the vector like described below ????: KoolMethod() { int *x = new int(); *x = 10; KoolList.Add(x); } Vector<int*>KoolList;

    Read the article

  • C vs C++ function questions

    - by james
    I am learning C, and after starting out learning C++ as my first compiled language, I decided to "go back to basics" and learn C. There are two questions that I have concerning the ways each language deals with functions. Firstly, why does C "not care" about the scope that functions are defined in, whereas C++ does? For example, int main() { donothing(); return 0; } void donothing() { } the above will not compile in a C++ compiler, whereas it will compile in a C compiler. Why is this? Isn't C++ mostly just an extension on C, and should be mostly "backward compatible"? Secondly, the book that I found (Link to pdf) does not seem to state a return type for the main function. I check around and found other books and websites and these also commonly do not specify return types for the main function. If I try to compile a program that does not specify a return type for main, it compiles fine (although with some warnings) in a C compiler, but it doesn't compile in a C++ compiler. Again, why is that? Is it better style to always specify the return type as an integer rather than leaving it out? Thanks for any help, and just as a side note, if anyone can suggest a better book that I should buy that would be great!

    Read the article

  • How do I remedy "Error: Cannot find module 'child-process-close'"?

    - by Tyler Sloan
    I was going about business as usual and about to checkout generator-angular-fullstack. I got no red errors but a message a the end saying Error: Cannot find module 'child-process-close'. I tried many a-thing–uninstalling node, reinstalling, manually getting rid of files and directories in local and/or global paths and tried to make sure Homebrew was the one who installed everything and somehow I've made things worse. (Also, I initially saw errors regarding karma. Everything looked right but it doesn't seem I did any good by throwing commands at it.) I am at a loss. All the stackoverflow questions have been clicked and I'm afraid I've probably tried too many of the suggestions. I cannot install any Yeoman generator. I cannot install anything with npm. When inside the project directory when I run npm install it throws the error. I really have no clue. Is there a way I can basically start over all together? A simple uninstall and install isn't cutting it. Something in the system needs to change but I don't know what. Any ideas?

    Read the article

  • getting the value of a pseudo-element with protractor

    - by bodine
    I'd like to verify the text content of a pseudo-element. The promise returned from using ptor.executeScript("window.getComputedStyle(jQuery('.my-class')[0], ':after').content").then(function(data){ console.log(arguments) // {'0':null} }); I've also tried dropping that in the expectation, but I'd guess that fails for the same reason. Since the CSS Declaration for this is pointing at one of the element's attributes anyway, should I just try to read that attribute?

    Read the article

  • Installing ngResource in Factory

    - by rackhamup
    I am trying to install ngResource into a factory like so: 'use strict'; var DTapp = angular.module('DeviceTraining'); /* Services */ DTapp.factory('Slides', ['ngResource', function($resource) { return $resource('slides/:slideID.json', {}, { query: {method:'GET', params:{slideID:'slides'}, isArray: true} }); }]); But I am getting this error message: Error: [$injector:unpr] Unknown provider: ngResourceProvider <- ngResource <- Slides Any help?

    Read the article

  • Is the Angular templateCache shared between apps? Is it persistent?

    - by alexp
    If I have two Angular apps that run on the same domain, will/can they share data in the templateCache? Or is the cache unique to each main application module? In general I'm trying to understand what dictates when a new templateCache is created. Furthermore I'm not clear on whether or in what way the templateCache is persistent? Looking in local storage and cookies, I don't see where anything is getting stored.

    Read the article

  • angular custom directive required validation is not updated

    - by Wouter Willems
    i created my own directive, replacing an input field with a custom made input field. However, the validation of the required field never seems to update and instead is always false. Other directives inside my directive like ng-class do work. I have created a plunker here to show this problem: http://plnkr.co/edit/NuZNAJceL0MVX8i6RK9n?p=preview Can anybody help me out how to make sure that the required validation is properly updated?

    Read the article

  • How can I match a twitter username with angular ui router

    - by user3929999
    I need to be able to match a path like '/@someusername' with angular ui router but can't figure out the regex for it. What I have are routes like the following $stateProvider .state('home', {url:'/', templateUrl:'/template/path.html'}) .state('author', {url:'/{username:[regex-to-match-@username-here]}'}) .state('info', {url:'/:slug', templateUrl:'/template/path.html'}) .state('entry', {url:'/:type/:slug', templateUrl:'/template/path.html'}); I need a bit of regex for the 'author' route that will match @usernames. Currently, everything I try is caught by the 'entry' route.

    Read the article

  • Running mysql query using node blocks the whole process and then timesout

    - by lobengula3rd
    I have a node javascript that uses mysql npm (Felix). I have a procedure stored in my DB which I call when the user selects an option to kind of create its own instance of the program. The user chooses for how long he wants that data to be initialized for him. This is suppsoed to be between 1 and 2 years. So if he choose 1 year this query will insert around 20,000 rows into 1 table. If I run this query and a local DB this takes around 30 seconds (I suppose it is reasonable because its a big query which should be done only once in 1 or 2 years so its ok). For some reason my node script freezes as if it can't handle any more calls from other users. The even worse problem is that after like 2 minutes my client ui gets like an error from the server. At this point not all the data that was supposed to enter the DB is entered. After waiting like another minute all the data finally gets to the DB and only then it will accept new requests. This is my connection: this.connection = mysql.createConnection({ host : '********rds.amazonaws.com', user : 'admin', password : '******', database : '*****' }); and this is my query function: this.createCourts = function (req, res, next){ connection.query('CALL filldates("' + req.body['startDate'] + '","' + req.body['endDate'] + '","' + req.body['numOfCourts'] + '","' + req.body['duration'] + '","' + req.body['sundayOpen'] + '","' + req.body['mondayOpen'] + '","' + req.body['tuesdayOpen'] + '","' + req.body['wednesdayOpen'] + '","' + req.body['thursdayOpen'] + '","' + req.body['fridayOpen'] + '","' + req.body['saturdayOpen'] + '","' + req.body['sundayClose'] + '","' + req.body['mondayClose'] + '","' + req.body['tuesdayClose'] + '","' + req.body['wednesdayClose'] + '","' + req.body['thursdayClose'] + '","' + req.body['fridayClose'] + '","' + req.body['saturdayClose'] + '");', function(err){ if (err){ console.log(err); } else return res.send(200); }); }; what am i missing here? as i understand connection.query should by async so why is it actually blocking my node script? thanks.

    Read the article

  • Can't get Angular Dart Router to work

    - by JesterXL
    I've tried this syntax in AngularDart 0.11.0: Angular Dart passing data from route service into a controller module.value(RouteInitializerFn, configureRoutes); void configureRoutes(Router router, RouteViewFactory views) { print("configureRoutes"); views.configure({ 'login': ngRoute( path: '/login', view: 'login/login.tpl.html'), 'today': ngRoute( path: '/today', view: '/today/today.tpl.html') }); However, my routing function never seems to get called. I've used both a print statement and breakpoint to no avail. When I attempt to call it like so: WorkoutLoggerApplication(this.rootScope, this.router) { print("WorkoutLoggerApplication::constructor"); new Future.delayed(new Duration(seconds: 2), () { router.go("login", {}); }); } I get: Bad state: Invalid route name: login I've tried 0.10.0, but no dice. I've also tried 3 varieties of the new bind function format, both also don't seem to ever fire the routing function.

    Read the article

< Previous Page | 17 18 19 20 21 22 23 24 25 26 27 28  | Next Page >