Search Results

Search found 2536 results on 102 pages for 'nested'.

Page 14/102 | < Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >

  • How can I cleanly turn a nested Perl hash into a non-nested one?

    - by knorv
    Assume a nested hash structure %old_hash .. my %old_hash; $old_hash{"foo"}{"bar"}{"zonk"} = "hello"; .. which we want to "flatten" (sorry if that's the wrong terminology!) to a non-nested hash using the sub &flatten(...) so that .. my %h = &flatten(\%old_hash); die unless($h{"zonk"} eq "hello"); The following definition of &flatten(...) does the trick: sub flatten { my $hashref = shift; my %hash; my %i = %{$hashref}; foreach my $ii (keys(%i)) { my %j = %{$i{$ii}}; foreach my $jj (keys(%j)) { my %k = %{$j{$jj}}; foreach my $kk (keys(%k)) { my $value = $k{$kk}; $hash{$kk} = $value; } } } return %hash; } While the code given works it is not very readable or clean. My question is two-fold: In what ways does the given code not correspond to modern Perl best practices? Be harsh! :-) How would you clean it up?

    Read the article

  • Turning a nested hash structure into a non-nested hash structure - is this the cleanest way to do it

    - by knorv
    Assume a nested hash structure %old_hash .. my %old_hash; $old_hash{"foo"}{"bar"}{"zonk"} = "hello"; .. which we want to "flatten" (sorry if that's the wrong terminology!) to a non-nested hash using the sub &flatten(...) so that .. my %h = &flatten(\%old_hash); die unless($h{"zonk"} eq "hello"); The following definition of &flatten(...) does the trick: sub flatten { my $hashref = shift; my %hash; my %i = %{$hashref}; foreach my $ii (keys(%i)) { my %j = %{$i{$ii}}; foreach my $jj (keys(%j)) { my %k = %{$j{$jj}}; foreach my $kk (keys(%k)) { my $value = $k{$kk}; $hash{$kk} = $value; } } } return %hash; } While the code given works it is not very readable or clean. My question is two-fold: In what ways does the given code not correspond to modern Perl best practices? Be harsh! :-) How would you clean it up?

    Read the article

  • binding nested json object value to a form field

    - by Jack
    I am building a dynamic form to edit data in a json object. First, if something like this exists let me know. I would rather not build it but I have searched many times for a tool and have found only tree like structures that require entering quotes. I would be happy to treat all values as strings. This edit functionality is for end users so it needs to be easy an not intimidating. So far I have code that generates nested tables to represent a json object. For each value I display a form field. I would like to bind the form field to the associated nested json value. If I could store a reference to the json value I would build an array of references to each value in a json object tree. I have not found a way to do that with javascript. My last resort approach will be to traverse the table after edits are made. I would rather have dynamic updates but a single submit would be better than nothing. Any ideas? // the json in files nests only a few levels. Here is the format of a simple case, { "researcherid_id":{ "id_key":"researcherid_id", "description":"Use to retrieve bibliometric data", "url_template" :[ { "name": "Author Detail", "url": "http://www.researcherid.com/rid/${key}" } ] } } $.get('file.json',make_json_form); function make_json_form(response) { dataset = $.secureEvalJSON(response); // iterate through the object and generate form field for string values. } // Then after the form is edited I want to display the raw updated json (then I want to save it but that is for another thread) // now I iterate through the form and construct the json object // I would rather have the dataset object var updated on focus out after each edit. function show_json(form_id){ var r = {}; var el = document.getElementById(form_id); table_to_json(r,el,null); $('body').html(formattedJSON(r)); }

    Read the article

  • Same route nested in multiple resources ember.js

    - by Daniel Upton
    I'm building an ember.js app which has a model called "Programme". A user can drill down to a programme by going: Genre > Subgenre > Programme or Folder > List > Programme Here's my router: this.resource('mylists', { path: '/' }, function() { this.resource('folder', { path: '/folder/:folder_id' }, function() { this.resource('list', { path: '/list/:list_id' }, function() { this.resource('programme', { path: '/programme/:programme_id' }); }); }); }); this.resource('catalogue', function() { this.resource('genre', { path: '/genre/:genre_id' }, function() { this.resource('subgenre', { path: '/subgenre/:subgenre_id' }, function() { this.resource('programme', { path: '/programme/:programme_id' }); }); }); }); The UI needs to be deeply nested (the genre view renders in the outlet of the catalogue template, the subgenre in the outlet of the genre template... and so forth). The problem I have is as both generated routes are called ProgrammeRoute when I linkTo the programme route inside the list template, it actually goes to the programme route nested in the subgenre route. What should I be doing here? To work around it I've named one route ListProgrammeRoute and SubgenreProgrammeRoute but that leads to some duplication.

    Read the article

  • Hierarchical/Nested Database Structure for Comments

    - by Stephen Melrose
    Hi, I'm trying to figure out the best approach for a database schema for comments. The problem I'm having is that the comments system will need to allow nested/hierarchical comments, and I'm not sure how to design this out properly. My requirements are, Comments can be made on comments, so I need to store the tree hierarchy I need to be able to query the comments in the tree hierarchy order, but efficiently, preferably in a fast single query, but I don't know if this is possible I'd need to make some wierd queries, e.g. pull out the latest 5 root comments, and a maximum of 3 children for each one of those I read an article on the MySQL website on this very subject, http://dev.mysql.com/tech-resources/articles/hierarchical-data.html The "Nested Set Model" in theory sounds like it will do what I need, except I'm worried about querying the thing, and also inserting. If this is the right approach, How would I do my 3rd requirement above? If I have 2000 comments, and I add a new sub-comment on the first comment, that will be a LOT of updating to do. This doesn't seem right to me? Or is there a better approach for the type of data I'm wanting to store and query? Thank you

    Read the article

  • Nested parsers in happy / infinite loop?

    - by McManiaC
    I'm trying to write a parser for a simple markup language with happy. Currently, I'm having some issues with infinit loops and nested elements. My markup language basicly consists of two elements, one for "normal" text and one for bold/emphasized text. data Markup = MarkupText String | MarkupEmph [Markup] For example, a text like Foo *bar* should get parsed as [MarkupText "Foo ", MarkupEmph [MarkupText "bar"]]. Lexing of that example works fine, but the parsing it results in an infinite loop - and I can't see why. This is my current approach: -- The main parser: Parsing a list of "Markup" Markups :: { [Markup] } : Markups Markup { $1 ++ [$2] } | Markup { [$1] } -- One single markup element Markup :: { Markup } : '*' Markups1 '*' { MarkupEmph $2 } | Markup1 { $1 } -- The nested list inside *..* Markups1 :: { [Markup] } : Markups1 Markup1 { $1 ++ [$2] } | Markup1 { [$1] } -- Markup which is always available: Markup1 :: { Markup } : String { MarkupText $1 } What's wrong with that approach? How could the be resolved? Update: Sorry. Lexing wasn't working as expected. The infinit loop was inside the lexer. Sorry. :) Update 2: On request, I'm using this as lexer: lexer :: String -> [Token] lexer [] = [] lexer str@(c:cs) | c == '*' = TokenSymbol "*" : lexer cs -- ...more rules... | otherwise = TokenString val : lexer rest where (val, rest) = span isValidChar str isValidChar = (/= '*') The infinit recursion occured because I had lexer str instead of lexer cs in that first rule for '*'. Didn't see it because my actual code was a bit more complex. :)

    Read the article

  • (nested) user controls within a mvp pattern causing sporadic problems

    - by LLEA
    hi everyone, I have a serious problem with nested user controls (UCs) in WinForms while trying to implement the mvp pattern (passive view). The project consists of one model (designed as a singleton) and a set of different presenters with corresponding view interfaces. To avoid one huge view interface and therefore an overloaded main UI, I decided to make use of a set of different UCs. Each UC has one view interface and one presenter that can access the model. But there are nested UCs: meaning that one specialised UC implements sort of a basic UC. The main UI just represents a container for all those UCs. So far, so good (if not, please ask)?! There are two problems that I am facing now (but I guess both are of the same origin): From time to time it is not possible anymore to load the UCs and test them within the Visual Studio 2008 User Control Test Container. The error message just says that a project with an output type of class library cannot be started directly etc. I can "handle" that by unloading all UC projects and reloading them afterwards. (I guess the references to all mvp components and other UCs are then updated). Assuming that the implementation of my mvp pattern is okay and all those UCs are testable within the VS Test Container at a certain time - there is the biggest problem still left: I am not able to add any UC (even the basic and unnested ones) to a simple Form (UI). The error message: error message.jpg Could it be that my basic UC causes all these Problems?! It consists of two simple ComboBoxes and implements a basic presenter and basic view interface. Whenever I add this UC to a different UC the VS designer adds two references to the public getter methods of the UC as resources. I then manually remove those resources from the resx-file and commend the corresponding lines in the designer file. thx in advance

    Read the article

  • CarrierWave and nested forms saving empty image object if photo :title is included in form

    - by Wasabi Developer
    I'm after some advice in regards to handling nested form data and I would be ever so grateful for any insights. The trouble is I'm not 100% sure why I require the following code in my model accepts_nested_attributes_for :holiday_image, allow_destroy: true, :reject_if => lambda { |a| a[:title].blank? } If I don't understand why I require to tact on on my accepts_nested_attributes_for association: :reject_if => lambda { |a| a[:title].blank? } If I remove this :reject_if lambda, it will save a blank holiday photo object in the database. I presume because it takes the :title field from the form as an empty string? I guess my question is, am I doing this right or is there a better way of this this within nested forms if I want to extend my HolidayImage model to include more strings like description, notes? Sorry If I can't be more succinct. My simple holiday app. # holiday.rb class Holiday < ActiveRecord::Base has_many :holiday_image accepts_nested_attributes_for :holiday_image, allow_destroy: true, :reject_if => lambda { |a| a[:title].blank? } attr_accessible :name, :content, :holiday_image_attributes end I'm using CarrierWave for image uploads. # holiday_image.rb class HolidayImage < ActiveRecord::Base belongs_to :holiday attr_accessible :holiday_id, :image, :title mount_uploader :image, ImageUploader end Inside my _form partial there is a field_for block <h3>Photo gallery</h3> <%= f.fields_for :holiday_image do |holiday_image| %> <% if holiday_image.object.new_record? %> <%= holiday_image.label :title, "Image Title" %> <%= holiday_image.text_field :title %> <%= holiday_image.file_field :image %> <% else %> Title: <%= holiday_image.object.title %> <%= image_tag(holiday_image.object.image.url(:thumb)) %> Tick to delete: <%= holiday_image.check_box :_destroy %> <% end %> Thanks again for your patience.

    Read the article

  • Python - Checking for membership inside nested dict

    - by victorhooi
    heya, This is a followup questions to this one: http://stackoverflow.com/questions/2901422/python-dictreader-skipping-rows-with-missing-columns Turns out I was being silly, and using the wrong ID field. I'm using Python 3.x here. I have a dict of employees, indexed by a string, "directory_id". Each value is a nested dict with employee attributes (phone number, surname etc.). One of these values is a secondary ID, say "internal_id", and another is their manager, call it "manager_internal_id". The "internal_id" field is non-mandatory, and not every employee has one. (I've simplified the fields a little, both to make it easier to read, and also for privacy/compliance reasons). The issue here is that we index (key) each employee by their directory_id, but when we lookup their manager, we need to find managers by their "internal_id". Before, when employee.keys() was a list of internal_ids, I was using a membership check on this. Now, the last part of my if statement won't work, since the internal_ids is part of the dict values, instead of the key itself. def lookup_supervisor(manager_internal_id, employees): if manager_internal_idis not None and manager_internal_id!= "" and manager_internal_id in employees.keys(): return (employees[manager_internal_id]['mail'], employees[manager_internal_id]['givenName'], employees[manager_internal_id]['sn']) else: return ('Supervisor Not Found', 'Supervisor Not Found', 'Supervisor Not Found') So the first question is, how do I check whether the manager_internal_id is present in the dict's values. I've tried substituting employee.keys() with employee.values(), that didn't work. Also, I'm hoping for something a little more efficient, not sure if there's a way to get a subset of the values, specifically, all the entries for employees[directory_id]['internal_id']. Hopefully there's some Pythonic way of doing this, without using a massive heap of nested for/if loops. My second question is, how do I then cleanly return the required employee attributes (mail, givenname, surname etc.). My for loop is iterating over each employee, and calling lookup_supervisor. I'm feeling a bit stupid/stumped here. def tidy_data(employees): for directory_id, data in employees.items(): # We really shouldnt' be passing employees back and forth like this - hmm, classes? data['SupervisorEmail'], data['SupervisorFirstName'], data['SupervisorSurname'] = lookup_supervisor(data['manager_internal_id'], employees) Thanks in advance =), Victor

    Read the article

  • IndexOutofRangeException while using WriteLine in nested Parallel.For loops

    - by Umar Asif
    I am trying to write kinect depth data to a text file using nested Parallel.For loops with the following code. However, it gives IndexOutofRangeException. The code works perfect if using simple for loops but it hangs the UI since the depth format is set to 640x480 causing the loops to write 307200 lines in the text file at 30fps. Therefore, I switched to Parallel. For scheme. If I omit the writeLine command from the nested loops, the code works fine, which indicates that the IndexOutofRangeException is arising at the writeline command. I do not know how to troubleshoot this. Please advise. Any better workarounds to avoid UI freezing? Thanks. using (DepthImageFrame depthImageframe = d.OpenDepthImageFrame()) { if (depthImageframe == null) return; depthImageframe.CopyPixelDataTo(depthPixelData); swDepth = new StreamWriter(@"E:\depthData.txt", false); int i = 0; Parallel.For(0, depthImageframe.Width, delegate(int x) { Parallel.For(0, depthImageframe.Height, delegate(int y) { p[i] = sensor.MapDepthToSkeletonPoint(depthImageframe.Format, x, y, depthPixelData[x + depthImageframe.Width * y]); swDepth.WriteLine(i + "," + p[k].X + "," + p[k].Y + "," + p[k].Z); i++; }); }); swDepth.Close(); } }

    Read the article

  • Python: Created nested dictionary from list of paths

    - by sberry2A
    I have a list of tuples the looks similar to this (simplified here, there are over 14,000 of these tuples with more complicated paths than Obj.part) [ (Obj1.part1, {<SPEC>}), (Obj1.partN, {<SPEC>}), (ObjK.partN, {<SPEC>}) ] Where Obj goes from 1 - 1000, part from 0 - 2000. These "keys" all have a dictionary of specs associated with them which act as a lookup reference for inspecting another binary file. The specs dict contains information such as the bit offset, bit size, and C type of the data pointed to by the path ObjK.partN. For example: Obj4.part500 might have this spec, {'size':32, 'offset':128, 'type':'int'} which would let me know that to access Obj4.part500 in the binary file I must unpack 32 bits from offset 128. So, now I want to take my list of strings and create a nested dictionary which in the simplified case will look like this data = { 'Obj1' : {'part1':{spec}, 'partN':{spec} }, 'ObjK' : {'part1':{spec}, 'partN':{spec} } } To do this I am currently doing two things, 1. I am using a dotdict class to be able to use dot notation for dictionary get / set. That class looks like this: class dotdict(dict): def __getattr__(self, attr): return self.get(attr, None) __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ The method for creating the nested "dotdict"s looks like this: def addPath(self, spec, parts, base): if len(parts) > 1: item = base.setdefault(parts[0], dotdict()) self.addPath(spec, parts[1:], item) else: item = base.setdefault(parts[0], spec) return base Then I just do something like: for path, spec in paths: self.lookup = dotdict() self.addPath(spec, path.split("."), self.lookup) So, in the end self.lookup.Obj4.part500 points to the spec. Is there a better (more pythonic) way to do this?

    Read the article

  • regressions with many nested categorical covariates

    - by eric
    I have a few hundred thousand measurements where the dependent variable is a probability, and would like to use logistic regression. However, the covariates I have are all categorical, and worse, are all nested. By this I mean that if a certain measurement has "city - Phoenix" then obviously it is certain to have "state - Arizona" and "country - U.S." I have four such factors - the most granular has some 20k levels, but if need be I could do without that one, I think. I also have a few non-nested categorical covariates (only four or so, with maybe three different levels each). What I am most interested in is prediction - given a new observation in some city, I would like to know the relevant probability/dependent variable. I am not interested as much in the related inferential machinery - standard deviations, etc - at least as of now. I am hoping I can afford to be sloppy. However, I would love to have that information unless it requires methods that are more computationally expensive. Does anyone have any advice on how to attack this? I have looked into mixed effects, but am not sure it is what I am looking for.

    Read the article

  • Modify passed, nested dict/list

    - by Gerenuk
    I was thinking of writing a function to normalize some data. A simple approach is def normalize(l, aggregate=sum, norm_by=operator.truediv): aggregated=aggregate(l) for i in range(len(l)): l[i]=norm_by(l[i], aggregated) l=[1,2,3,4] normalize(l) l -> [0.1, 0.2, 0.3, 0.4] However for nested lists and dicts where I want to normalize over an inner index this doesnt work. I mean I'd like to get l=[[1,100],[2,100],[3,100],[4,100]] normalize(l, ?? ) l -> [[0.1,100],[0.2,100],[0.3,100],[0.4,100]] Any ideas how I could implement such a normalize function? Maybe it would be crazy cool to write normalize(l[...][0]) Is it possible to make this work?? Or any other ideas? Also not only lists but also dict could be nested. Hmm... EDIT: I just found out that numpy offers such a syntax (for lists however). Anyone know how I would implement the ellipsis trick myself?

    Read the article

  • Ruby on Rails - pass variable to nested form

    - by Krule
    I am trying to build a multilingual site using Rails, but I can't figure out how to pass variable to nested form. Right now I am creating nested form like this. @languages.each do @article.article_locale.build(:language_id => language.id) end But i would like to pass value of language to it so i can distinguish fields. Something like this. @languages.each do |language| @language = language @article.article_locale.build(:language_id => language.id) end However, I always end up with language of the last loop iteration. Any way to pass this variable? -- edit -- In the end, since I've got no answer I have solved this problem so it, at least, works as it should. Following code is my partial solution. In model: def self.languages Language.all end def self.language_name language = [] self.languages.each_with_index do |lang, i| language[i] = lang.longname end return language end In Controller: def new @article = Article.new Article.languages.each do |language| @article.article_locale.build(:language_id => language.id) end end In HAML View: -count = 0 -f.fields_for :article_locale do |al| %h3= Article.language_name[count] -count+=1 -field_set_tag do %p =al.label :name, t(:name) =al.text_field :name %p =al.label :description, t(:description) =al.text_area :description =al.hidden_field :language_id It's not the most elegant solution I suppose, but it works. I would really love if I could get rid of counter in view for instance.

    Read the article

  • Creating nested fields for column on assignment table?

    - by H O
    I have three models, that represent a many to many relationship - Product, Sale and Product_sale. I have a nested form that allows me to create new products from the sale form - so far, so good. I have, however, added some additional fields to the assignment table - price, for example. How can I set the price on the assignment table from the product form, when it is nested in the sale form? I currently have the code below: <%= sale.fields_for :products do |products_builder| %> <%= render :partial => "products/form", :locals => {:f => products_builder, :form_actions_visible => false} %> <% end -%> I could nest a Product_sale form within the product form, but this would create a new product_sale, which is not what I am looking for. I will most likely need to nest the price field within the product form, to ensure that it updates the correct assignment record (since there could be multiple products on one sale form). How can I use a fields_for loop on the product form to update the existing assignment record that is built when I do @sale.products.build? The assignment record will not yet be saved, so I can not access it using a where clause and edit it that way. Thanks!

    Read the article

  • Nested <a> and <span> challenge

    - by PaddyO
    Hi all, Trying in vain to get a nested link working within a nested span. This is a working test page for the code below to explain what I'm trying to do. Any ideas on how to get this working in valid html? I guess it's either a nesting order or style syntax thing but I am at a loss. Any thoughts much appreciated. <div id="greyback"> <ul id="scrollbox"> <li class="listcat">List header</li> <li><a class="menu" href="#freeze">List item 1<span><b>This text has popped up because you have clicked the list item, which has an "a" tag and now has :focus. That "a" tag is the first of two.</b><br><br>What I am trying to do is to set the second "a" tag as a DIFFERENT "embedded" link in this box<span style="color: blue; background-color: yellow;">eg, here<a href="http://www.conservationenterprises.com" target="blank">This is the second (nested) "a" tag in this html nest. It is a link to an external site. Instead of this being an always-visible link, I want it to sit within the yellow box in the first span (click the List item 1 to display).</a></span> </a></span> </li> </a></span> </li> </ul> </div> and the CSS: #scrollbox {margin: 0 auto; margin-top: 1em; margin-bottom: 1em; width:19em; height:auto; max-height: 21em; overflow:auto; border-bottom: 0.1em solid #FFA500; border-top: 0.1em solid #FFA500;} #scrollbox a {float: left; color:#000000; text-decoration:none; width:18em; height: auto; margin-bottom: 0.5em; font-family: Arial, sans-serif; font-size: 0.9em; text-align:left;} #scrollbox a.menu {} #scrollbox a span {display:none; position:absolute; left:0em; top:0;} #scrollbox a span img {float: right; border:0; max-width:7.5em;} #scrollbox a:hover {border: 0; color: #7ebb11; font-size:0.9em;} #scrollbox a:hover span {border: 0; color: #535353;} #scrollbox a span:focus {color: blue;} #scrollbox a:active {border:none; color: #535353; text-decoration: none;} #scrollbox a:focus {border:0em solid #000; outline:0;} #scrollbox a:active span, #scrollbox li a:active span, #scrollbox a:focus span, #scrollbox li a:focus span {display: block; width: 52.5em; min-height: 20em; height: auto; left: 1.5em; top:18em; z-index:10; font-size:0.9em; text-align: left; padding: 1em; padding-bottom: 0em; background-color: #c3FFe3; color: #535353; border: solid #FFA500 0.25em;} #scrollbox li a:active span span, #scrollbox li a:focus span span{display: block; width: auto; height: auto; min-height: 2em; left: 25em; top:10em; z-index:10; font-size:0.9em; text-align: left; padding: 1em; padding-bottom: 0em; background-color: transparent; color: #535353; border: dashed red 1px;} .ul#scrollbox {padding-left: 0.1em;} #scrollbox li {float:left; list-style: none; background: url(blank.png) no-repeat left center; margin-left: 0em; font-family:Arial, sans-serif; font-size: 0.9em;} #scrollbox li.listcat {float: left; text-align:left; width: 18em; margin-left: 0em; margin-top: 0.1em; margin-bottom: 0.3em; padding-top:0.5em; color: green; font-size: 0.9em; font-weight:bold;} Cheers Patrick.

    Read the article

  • Python performance: iteration and operations on nested lists

    - by J.J.
    Problem Hey folks. I'm looking for some advice on python performance. Some background on my problem: Given: A mesh of nodes of size (x,y) each with a value (0...255) starting at 0 A list of N input coordinates each at a specified location within the range (0...x, 0...y) Increment the value of the node at the input coordinate and the node's neighbors within range Z up to a maximum of 255. Neighbors beyond the mesh edge are ignored. (No wrapping) BASE CASE: A mesh of size 1024x1024 nodes, with 400 input coordinates and a range Z of 75 nodes. Processing should be O(x*y*Z*N). I expect x, y and Z to remain roughly around the values in the base case, but the number of input coordinates N could increase up to 100,000. My goal is to minimize processing time. Current results I have 2 current implementations: f1, f2 Running speed on my 2.26 GHz Intel Core 2 Duo with Python 2.6.1: f1: 2.9s f2: 1.8s f1 is the initial naive implementation: three nested for loops. f2 is replaces the inner for loop with a list comprehension. Code is included below for your perusal. Question How can I further reduce the processing time? I'd prefer sub-1.0s for the test parameters. Please, keep the recommendations to native Python. I know I can move to a third-party package such as numpy, but I'm trying to avoid any third party packages. Also, I've generated random input coordinates, and simplified the definition of the node value updates to keep our discussion simple. The specifics have to change slightly and are outside the scope of my question. thanks much! f1 is the initial naive implementation: three nested for loops. 2.9s def f1(x,y,n,z): rows = [] for i in range(x): rows.append([0 for i in xrange(y)]) for i in range(n): inputX, inputY = (int(x*random.random()), int(y*random.random())) topleft = (inputX - z, inputY - z) for i in xrange(max(0, topleft[0]), min(topleft[0]+(z*2), x)): for j in xrange(max(0, topleft[1]), min(topleft[1]+(z*2), y)): if rows[i][j] <= 255: rows[i][j] += 1 f2 is replaces the inner for loop with a list comprehension. 1.8s def f2(x,y,n,z): rows = [] for i in range(x): rows.append([0 for i in xrange(y)]) for i in range(n): inputX, inputY = (int(x*random.random()), int(y*random.random())) topleft = (inputX - z, inputY - z) for i in xrange(max(0, topleft[0]), min(topleft[0]+(z*2), x)): l = max(0, topleft[1]) r = min(topleft[1]+(z*2), y) rows[i][l:r] = [j+1 for j in rows[i][l:r] if j < 255]

    Read the article

  • Accessing nested HashMaps in Java

    - by mridang
    Hi, I have a HashMap in Java, the contents of which (as you all probably know) can be accessed by HashMap.get("keyname"); If a have a HashMap inside another HashMap i.e. a nested HashMap, how would i access the contents? Can i do this like this, inline: HashMap.get("keyname").get("nestedkeyname"); Thank you.

    Read the article

  • How to create nested macro in BOO

    - by Neo
    Hi, I am creating nested macros in BOO, I wrote this program: macro text: macro subMacro: text["Text"] = "Hello World" return [| block: System.Console.WriteLine( "Hello World" ); |] But I am getting the error "Unknown Identifer: 'text'" in the 3rd line of the code.

    Read the article

  • MongoDB Norm query nested objects

    - by Howard
    Does anyone have a sample of how to query for nested/inner objects in MongoDB using NORM (C#)? For example, if a typical document in a collection looks like Order/OrderItems, how can I look up a specific OrderItem by OrderItem.Quantity 10.

    Read the article

  • C# - Coding a nested stateflow diagram

    - by weberc2
    I have the following state diagram. I know how to make a simple state machine that transitions between non-nested states; however, I don't know how to transition between nested states. Could someone explain how to do this at an appropriately high level (i.e., you don't need to write the code for me--unless you're feeling particularly generous :P). State Diagram [EDIT: The bottom "A", "C", and "E" should be "B", "D", and "F" respectively; sorry!] What I know how to do public class MyState : State // State enumeration { public static MyState A = new MyState("State A"); public static MyState B = new MyState("State B"); public static MyState C = new MyState("State C"); public static MyState D = new MyState("State D"); public static MyState E = new MyState("State E"); public static MyState F = new MyState("State F"); public static MyState NEUT = new MyState("Neutral"); public static MyState P = new MyState("P"); protected MyState(string name) : base(name) { } } public class MyEvent : Event // Event enumeration { public static MyEvent X_POS = new MyEvent("X+"); public static MyEvent X_NEG = new MyEvent("X-"); public static MyEvent Y_POS = new MyEvent("Y+"); public static MyEvent Y_NEG = new MyEvent("Y-"); protected MyEvent(string name) : base(name) { } } public class MyStateMachine : StateMachine<MyState, MyEvent> // State Machine implementation { public MyStateMachine() : base(MyState.P) // MyState.P = initial state { // Set up the transition table // P this.addTransition(MYState.P, MyState.NEUT, MyEvent.Y_NEG); // NEUTRAL this.addTransition(MyState.NEUT, MyState.P, MyEvent.Y_POS); this.addTransition(MyState.NEUT, MyState.A, MyEvent.Y_NEG); this.addTransition(MyState.NEUT, MyState.B, MyEvent.Y_POS); this.addTransition(MyState.NEUT, MyState.C, MyEvent.Y_NEG); this.addTransition(MyState.NEUT, MyState.D, MyEvent.Y_POS); this.addTransition(MyState.NEUT, MyState.E, MyEvent.Y_NEG); this.addTransition(MyState.NEUT, MyState.F, MyEvent.Y_POS); // A this.addTransition(MyState.A, MyState.NEUT, MyEvent.Y_POS); // B this.addTransition(MyState.B, MyState.NEUT, MyEvent.Y_NEG); // C this.addTransition(MyState.C, MyState.NEUT, MyEvent.Y_POS); // D this.addTransition(MyState.D, MyState.NEUT, MyEvent.Y_NEG); // E this.addTransition(MyState.E, MyState.NEUT, MyEvent.Y_POS); // F this.addTransition(MyState.F, MyState.NEUT, MyEvent.Y_NEG); } public void move(MyEvent eevent) { try { this.moveNext(eevent); } catch (Exception e) { } } }

    Read the article

  • jQuery / javascript and nested if statements

    - by rayne
    I have a multi-lingual page where I want to display form validation error in the user's language. I use a hidden input to determine which language version the user is browsing like this: <input type="hidden" name="lang" id="lang" value="<?php echo $lang; ?>" /> The PHP side of the script works, but jQuery doesn't seem to realize which language is passed on. It displays the English error message no matter on which language site I am. Here's the code (I removed the other form fields for length): $(document).ready(function(){ $('#contact').submit(function() { $(".form_message").hide(); var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/; var lang = $("#lang").val(); var name = $("#name").val(); var dataString = { 'lang': lang, 'name': name } if (name == '') { if (lang == 'de') { $("#posted").after('<div class="form_message"><p><span class="error">Fehler:</span> Bitte gib deinen Namen an!</p></div>'); } else { $("#posted").after('<div class="form_message"><p><span class="error">Error:</span> Please enter your name!</p></div>'); } $("#name").focus(); $("#name").addClass('req'); } else { $("#loading").show(); $("#loading").fadeIn(400).html('<img src="/img/loading.gif" />Loading...'); $.ajax({ type: "POST", url: "/contact-post.php", data: dataString, cache: false, success: function(html){ $("#loading").hide(); $("#posted").after('<div class="form_message"><p>Thank you! Your contact request has been sent.</p></div>'); $("#contact input:submit").attr("disabled", "disabled").val("Success!"); } }); }return false; }); }); The problem seems to be somewhere in the nested if statement. Does jQuery / javascript even recognize nested ifs? And if yes, why is it not working?

    Read the article

  • Rails nested URL question

    - by Jacobo Tibaquira
    Hi Im having issues with RESTful URLs in Rails. I have site.com/services url, and I want to have subpages under that category, thats it: site.com/services/arquitecture, site.com/services/plumbing, etc. The pages that im serving under that category are "static" .rhtml files and I would want them to be on the same controller. Is there a way of doing this? I've tried nested resources but I find it hard to fully understand. Thanks

    Read the article

  • jsTree Selecte most nested node

    - by niao
    Greetings, I just started to use jsTree and I have a question for you guys. How can I select only the most nested node - the node which doesn't have any children. additionally, when this node is selected, I would like to submit my form which contains the jsTree. How can I then access selected node?

    Read the article

< Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >