Recent Entries 10
- pattern minor 112d agoNested loop to render tiles in a gridThis code works but I'm not really sure if I wrote it good enough. It seems a bit vague but I can't really assess it properly. I'm particularly concerned with the `xAxis` variable. I don't like how I have to initialize it inside the first loop. I would rather have it next to `yAxis`. Is this a problem? ``` float yAxis = SPACE_BETWEEN_TILES; float xAxis; for(int i = 0; i < 3; i++) { xAxis = SPACE_BETWEEN_TILES; for(int v = 0; v < 3; v++) { shapeRenderer.rect(xAxis, yAxis, 10, 10); xAxis = TILE_WIDTH_AND_HEIGHT + xAxis; } yAxis = yAxis + TILE_WIDTH_AND_HEIGHT; } ```
- pattern minor 112d agoSumming up distinct elements in stepsMy current task is to find a score from an array where the highest/lowest scores have been taken away, and if the highest/lowest occur more than once (ONLY if they occur more than once), one of them can be added: E.g. `int[] scores = [4, 8, 6, 4, 8, 5]` therefore the final addition will be \$\sum{4,8,6, 5} = 23 \$. Another condition of the task is that LINQ cannot be used, as well as any of the `System.Array` methods (you can see by my previously ask questions that has been a bit of a pain for me, since I solved this with LINQ in less than 5 minutes). I have working code the solves the problem but the task requires multiple methods/functions. I have been trying to restructure the program but with all sorts of issues. ``` using System; using System.Collections.Generic; //using System.Linq; using System.Text; using System.Threading.Tasks; namespace Scoring { class Program { static int highOccurrence = 0; static int lowOccurrence = 0; //static int high; scores[i]) { low = scores[i]; } //record lowest value if (high 1) { //if there is more than 1 high (or 1 low) it is added once into the total total += high; if (lowOccurrence > 1) { total += low; } } Console.WriteLine("Sum = " + total); return total; //remove not all code paths return.. error } static void ExitProgram() { Console.Write("\n\nPress any key to exit program: "); Console.ReadKey(); }//end ExitProgram } } ``` I have placed arrows in the code above to show where my issue is. If I try to declare "high" and "low" as global variables, my final answer is always a few numbers off, buy if I leave the variables declared as `high = scores[0]` etc, I will get the right answer. What I want ideally is to have separate methods for each step of the calculation, so right now I have method for finding the number of times a specific value shows up in the
- pattern minor 112d agoHandling signals in Python inside a functionI have code that needs to exit gracefully. To simplify things, I am presenting an example based on the answer given here. Since I need to handle a few signals, I thought of putting this logic in a function: ``` def set_signals(): original_sigint = signal.getsignal(signal.SIGINT) signal.signal(signal.SIGINT, exit_gracefully) signal.signal(signal.SIGTERM, exit_gracefully) signal.signal(signal.SIGINT, exit_gracefully) signal.signal(signal.SIGALRM, exit_gracefully) signal.signal(signal.SIGHUP, signal.SIG_IGN) ``` Thus, the main block of the python code should be: ``` if __name__ == '__main__': # store the original SIGINT handler set_signals() run_program() ``` This will fail however, since the `exit_gracefully` does not know the variable `original_init`. Therefore, my solution was to create `original_sigint` as a global variable. ``` import signal import time import sys original_sigint = None def run_program(): while True: time.sleep(1) print("a") def exit_gracefully(signum, frame): # restore the original signal handler as otherwise evil things will happen # in raw_input when CTRL+C is pressed, and our signal handler is not re-entrant global original_sigint signal.signal(signal.SIGINT, original_sigint) try: if raw_input("\nReally quit? (y/n)> ").lower().startswith('y'): sys.exit(1) except KeyboardInterrupt: print("Ok ok, quitting") sys.exit(1) # restore the exit gracefully handler here signal.signal(signal.SIGINT, exit_gracefully) def set_signals(): global original_sigint original_sigint = signal.getsignal(signal.SIGINT) signal.signal(signal.SIGINT, exit_gracefully) signal.signal(signal.SIGTERM, exit_gracefully) signal.signal(signal.SIGINT, exit_gracefully) signal.signal(signal.SIGALRM, exit_gracefully) signal.signal(signal.SIGHUP, signal.SIG_IGN) if __name__ == '__main__': # store the original SIGINT hand
- pattern minor 112d agoCommunicating between plugins whilst maintaining context in JavascriptI'm making some changes to a JavaScript plugin on a site I've been made steward over. This main plugin has it's own sub-plugins and I'm trying to make certain aspects modular. Currently, I'm attempting to make a reusable modal window that the sub-plugins ferry data to. This main plugin uses extensive use of prototype. Right now, the main `Plugin` calls the sub-plugins `"callback"` method. The callback method then calls the `Plugin.prototype.openModal` and supplies it with a html template (html), callback function (what should be done after everything is done), validation (function that will validate the inputs of the modal, if present), and prerender (function that is fired before the modal is launched). My code is pretty pseudo-cody, but this is what I have: Prototype for reusable modal window, contained in main plugin: ``` Plugin.prototype.openModal = function(html, callback, validation, prerender) { var self = this; var headerFragment = html.hasOwnProperty('header') ? html.header : '', bodyFragment = html.hasOwnProperty('body') ? html.body : '', closeButtonText = html.hasOwnProperty('closeText') ? html.closeText : 'Cancel', confirmButtonText = html.hasOwnProperty('confirmText') ? html.confirmText : 'Save changes'; // Only create the modal when it's called for the first time! if(!document.getElementById('confirm-modal')) this.createModal(); var modal = $('#modal'); modal.find('.modal-header h3').html(headerFragment); modal.find('.modal-body').html(bodyFragment); modal.find('.close-btn').html(closeButtonText); modal.find('.confirm-btn').html(confirmButtonText); modal.find('.modal-validation span').text(''); if(typeof prerender === 'function') prerender(); function closeModal(input) { if(callback && typeof callback === 'function') { input = input ? input : $('#modal').find('input').val(); callback.call(self, input); } $('#modal').modal('hide'); } function handleAlert(text) { var
- pattern minor 112d agoConway's Game of Life - Conventional JavaScript?I'm using the Game of Life Kata to help me learn JavaScript. I've picked up the syntax through Codecademy tutorials, but my current skill level is Novice. The example code has working functionality for initialising a `World` with live cells and asking it to 'tick'. All suggestions for improvement are welcome. I'd especially like feedback on the following: - JavaScript idioms and conventions - Function and variable scoping - Making use of built-in functions and datatypes ``` myapp = {}; /** * World represents a 2 dimensional square matrix of cells. * @param dimension * @param liveCellCoordinates * @returns {myapp.World} */ myapp.World = function(dimension, liveCellCoordinatesArray) { this.dimension = dimension; this.liveCellCoordinates = liveCellCoordinatesArray; }; /** * * @returns {Array} of live cells after tick. */ myapp.World.prototype.tick = function() { var nextGenerationOfLiveCells = []; // for each cell in world for(var y=0; y>> liveNeighbours of ", x, y, ": ", liveNeighbours); return liveNeighbours; }; myapp.World.prototype.isCellAlive = function(x, y) { for(var cell in this.liveCellCoordinates) { if(x === this.liveCellCoordinates[cell][0] && y === this.liveCellCoordinates[cell][1]) { return true; } } return false; }; function isBorn(liveNeighbours) { return liveNeighbours === 3; } function isSurvivor(liveNeighbours) { return liveNeighbours === 2 || liveNeighbours === 3; } ```
- pattern moderate 112d agoAdvice needed for scopes in JavaScriptI would like to connect this "JS" to Bugzilla (example: bugzilla.mozilla.org or landfill.bugzilla.org). I started to learn JS language today and I would like to ask you: - How can I not do bad things in global scope? - How should I use functions (in `var` or not)? ``` quicksearch = document.getElementById('quicksearch_top'); comment = document.getElementById('comment'); severity = document.getElementById('bug_severity'); priority = document.getElementById('priority'); commit_top = document.getElementById('commit_top'); commit = document.getElementById('commit'); function focusonload() { // may be it should be // in next function? function cursorfocus(s) { x = window.scrollX; y = window.scrollY; s.focus(); window.scrollTo(x, y); } if (comment !== null) { cursorfocus(comment) } else { quicksearch.focus(); } } function navigation(keypressed) { keypressed = keypressed || window.event; function selectelement(w, select) { w.value = select; } keyCode = keypressed.keyCode || keypressed.which, kn = { enter: 13, save: 83, down: 40, up: 38, p1: 49, p2: 50, p3: 51, p4: 52, p5: 53, }; if (keypressed.altKey) { if (keyCode == nk.save && commit_top!==null){ commit_top.click(); } var key_str; if (priority!==null){ switch (keyCode) { case kn.p1: key_str = "P1"; break; case kn.p2: key_str = "P2"; break; case kn.p3: key_str = "P3"; break; case kn.p4: key_str = "P4"; break; case kn.p5: key_str = "P5"; break; } } selectelement(priority, key_str); severity.focus(); } else if (keypressed.ctrlKey) { switch (keyCode) { case kn.enter: if (commit!==null&&comment.value!=="") {
- pattern critical 112d agoReturn pointer to local structI see some code samples with constructs like this: ``` type point struct { x, y int } func newPoint() *point { return &point{10, 20} } ``` I have C++ background and it seems like error for me. What are the semantic of such construct? Is new point allocated on the stack or heap?
- pattern critical 112d agoIs it possible to declare two variables of different types in a for loop?Is it possible to declare two variables of different types in the initialization body of a for loop in C++? For example: ``` for(int i=0,j=0 ... ``` defines two integers. Can I define an `int` and a `char` in the initialization body? How would this be done?
- pattern critical 112d agoIs there a reason for C#'s reuse of the variable in a foreach?When using lambda expressions or anonymous methods in C#, we have to be wary of the access to modified closure pitfall. For example: ``` foreach (var s in strings) { query = query.Where(i => i.Prop == s); // access to modified closure ... } ``` Due to the modified closure, the above code will cause all of the `Where` clauses on the query to be based on the final value of `s`. As explained here, this happens because the `s` variable declared in `foreach` loop above is translated like this in the compiler: ``` string s; while (enumerator.MoveNext()) { s = enumerator.Current; ... } ``` instead of like this: ``` while (enumerator.MoveNext()) { string s; s = enumerator.Current; ... } ``` As pointed out here, there are no performance advantages to declaring a variable outside the loop, and under normal circumstances the only reason I can think of for doing this is if you plan to use the variable outside the scope of the loop: ``` string s; while (enumerator.MoveNext()) { s = enumerator.Current; ... } var finalString = s; ``` However variables defined in a `foreach` loop cannot be used outside the loop: ``` foreach(string s in strings) { } var finalString = s; // won't work: you're outside the scope. ``` So the compiler declares the variable in a way that makes it highly prone to an error that is often difficult to find and debug, while producing no perceivable benefits. Is there something you can do with `foreach` loops this way that you couldn't if they were compiled with an inner-scoped variable, or is this just an arbitrary choice that was made before anonymous methods and lambda expressions were available or common, and which hasn't been revised since then?
- pattern critical 112d agoWhat is the scope of variables in JavaScript?What is the scope of variables in javascript? Do they have the same scope inside as opposed to outside a function? Or does it even matter? Also, where are the variables stored if they are defined globally?