instruction
stringlengths
71
71.9k
For educational purposes I've tried to implement a simple algebraic OOP example using CLOS. The functionality is as far as I can say as it is supposed to be. The intended approach was to implement a simple example of ideomatic OOP polymorphism. For a greater learning experience I've wanted to show the code to get sugge...
This is for an instrumentation tool using the ASM tree api. This method assigns a handler to a field, which is used in instrumented methods. As a result of my instrumentation, the instrumented class implements an interface and is a handler itself, so a value of this behaves like a NullObject concerning handled methods ...
Assume a 2D [n][n] matrix of 1's and 0's. All the 1's in any row should come before 0's. The number of 1's in any row I should be at least the number of 1's row (i+1). Find a method and write a C program to count the number of 1's in a 2D matrix. The complexity of the algorithm should be order n. The question is from...
I have 16 permutations each with 104 variables using the standard alphabet. The 104 variable permutation is selected based off of compression complexity. This is one example of the pattern I am able to generate it has a low compression ratio of 1.3 with overhead: HHHFHHFFHHFHHFFHHFHHHFHAAAAHHHFHHFFHHFHHFFHHFHHHFHAAAAH...
I started learning C a week ago, and here is my implementation for the split function: char** my_split(const char* str, char delim, int* size) { int index = 0, start; char** results = NULL; *size = 0; do { if ((*size) % 10 == 0) //top floor reached { results = realloc(re...
playerObject is an NSDictionary from JSONObjectWithData:options:error. I'm trying to update a CoreData entity. if ([results count] > 0) { newPlayer = (Player *)[results objectAtIndex:0]; } else { //Add a new player newPlayer = [NSEntityDescription insertNewObjectForEntityForName:@"Player" inManagedObjectCon...
import java.util.ArrayList; public class SumsOfPerfectPowers { ArrayList<Long> numList = new ArrayList<Long>(5000001); // status of whether a number is power number boolean[] result = new boolean[5000001]; public SumsOfPerfectPowers() { numList.add((long) 0); numList.add((long) 1); ...
I have this kind of file structure MALE:FooBar:32 FEMALE:BarFoo:23 Where I would want to identify the gender and age of person, <Gender>:<Name>:<age> try{ BufferedReader in = new BufferedReader(new FileReader("people.ser")); String s; while((s = in.readLine()) != null){ String[] var = s.split("...
I am new to programming and have written this Data Access Layer. I am using this DAL in my projects. Now, I have a feeling that it is pathetic (when I wrote it, I was kind of happy). Do you guys also feel the same for this DAL. Kindly help me write a better one. There is no Transaction in my DAL and I have no idea how ...
I tried to solve the Unfriendly Number problem on InterviewStreet: There is one friendly number, K, and N unfriendly numbers. We want to find how many numbers are there which exactly divide the friendly number, but does not divide any of the unfriendly numbers. \$1 \le N \le 10^6\$ \$1 \le K \le 10^13\$ \$1 \le\$...
I often get lines like this in my Apache error log: File does not exist: /path/to/www/data:image/gif;base64,R0lGODlhBgAGAIAOAP/yH5BAEACAEALAAAAAAGGAYAAAIJhB0Xi5vOoFwFADs= Obviously, this is due to somebody using an outdated browser (or a robot) which doesn't handle inline images (Data URI/base64 encoded). I am thinki...
I am trying to simplify the following massive conditional statement but have no idea how to. Does anyone have suggestions for it? //regular elements use the normal position variables. var tooltipXPos = xPos; var tooltipYPos = yPos-$tooltipElement.height()-YOffset; //individual elements position shifting... //for sub_...
Similar to, but distinct from Poker hand identifier. I'm working towards solving this kata. The below code doesn't print the result yet, and it reads hand strings rather than game strings. Take 4: import Data.String import Data.List import Data.Ord data Rank = Two | Three | Four | Five | Six | Seven | Eight | Nine ...
I have a database schema for a game to hold save files where some tables have a one-to-one relationship to classes. I was wondering if I should split up some tables. Example: troop_class table. It could have a PK of { GameID,PostionX,PostionY,PostionZ,Team } but then team don't really rely on the positions and coul...
I'm developing a JS-based app that allows you to customize a product. I still consider myself a super newbie to javascript and especially to object oriented programming. So far, so good, the app does what I want it to do, so no trouble there. My background is mostly in jQuery, so my main concern is how I'm sharing and ...
I put together this code to for the Udacity cs101 exam. It passes the test, but I feel their must be a more elegant way to manage this problem. Some help from a module (like itertools). Question 8: Longest Repetition Define a procedure, longest_repetition, that takes as input a list, and returns the element in the li...
I'm making a simple httpcode monitor as an example for teaching myself PHP OOP. I have written the code below and would be interested in having it improved. In particular, I'm not sure about this line: $httpcode = $website->get_httpcode($url); This seems very inefficient to me as I have to to pass the URL back to the ...
I have a list of friends and new friends are added via a form. When you click on a friend you see all the information about him. There is also an Edit button. When clicking it, I want a form to be displayed (the same as the form for adding) but already filled with the current information about the friend. It is workin...
forceTwoDigits = (val) -> if val < 10 return "0#{val}" return val formatDate = (date) -> year = date.getFullYear() month = forceTwoDigits(date.getMonth()+1) day = forceTwoDigits(date.getDate()) hour = forceTwoDigits(date.getHours()) minute = forceTwoDigits(date.getMinutes()) second = forceTwoDigits...
I have a byte array in a C# program. I want to determine as quickly as possible if the content is Xml. If it's the case, I also want to return the Xml itself. By now I have this method : protected bool TryGetXElement(byte[] body, out XElement el) { el = null; // if there is no data, this is not ...
The errors are passed through every callback, but in fact, it might be better to throw an error at higher levels. For example, look at the mongodb.js database function. It passes through an error in the callback. However, if there was an error at that level, it might be better to deal with it at that point and just fal...
I am studying descriptors. They work with class varibles out of the box, but I want them to operate on instance variables too, so I did this: class NumberDescriptor(object): def __init__(self,name): self.name = name def __set__(self, instance, value): if not isinstance(value, int): ...
I have an ASP.NET MVC3 web application that displays a list of parts (a part is a simple entity with a number and a description). I have updated the action method to support filtering and paging: [HttpGet] public ViewResult Index(int page = 1, int pageSize = 30, string filter = "All") { IEnumerable<Part> parts; ...
I'm toggling on/off series in chart and was wondering if I was doing anything crazy. Is the atom really a good idea here? ;; ================ Graph data ================ (def serie1 {:label "Bar" :data [[11 13] [19 11] [30 -7]]}) (def serie2 {:label "Foo" :data [[10 1] [17 -14] [30 5]]}) (def serie3 {:label "Zon" :dat...
Here is a Python script I wrote earlier for rapidly requesting a file from a server and timing each transaction. Can I improve this script? from time import time from urllib import urlopen # vars url = raw_input("Please enter the URL you want to test: ") for i in range(0,100): start_time = time() pic = urlope...
I just spent some time putting together a simple protocol and implementation for packetizing byte streams (on GitHub here). The project is aimed at embedded systems that need a very lightweight way to pass discrete messages across serial lines. Since I've never had any of my C reviewed before, would you mind taking a l...
This is from a C# library I'm writing that checks for updates through a PHP script. public bool CheckForUpdate(Request Request) { HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(UpdateServerAddress + "http://{0}/update.php?{1}" + Request.ToString()); httpRequest.UserAgent = "KMUpdaterClient/"...
I was using such code: class Counter { private int i = 0; public int Next() { lock (this) { return i++; } } public void Reset() { lock (this) { i = 0; } } } I refactored it such a way: class Counter { private int...
I have to check a given amount of regular expressions, which are defining number ranges for dial plans, against an input number range. The target is to check and see, if any of the numbers in the range are free, or which regular expression matches for the number. Last situation is said to be an occupied number, otherwi...
I know there are some answers about a user function to split chars and I have one already running (found one years ago in the net and modified it to my own needs). Since I use this function very often, I'd like to ask the best SQL professionals (which are probably here) to review this function for performance. Is the f...
Let me start with a little introduction. I am in the process of learning OOP in PHP. I have also researched Design Patterns but have not yet fully grasped the different types of concepts. I am at the stage where every few months I realise that I am not doing things the correct way and have to change my style. This is s...
I am just trying to use ASP.NET MVC using repository pattern. Could somebody see If I am doing something wrong here. Model - Contains the model public class Contact { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string ...
I'm a Pthreads newbie and I've been giving myself a challenge: I want to have a resource that multiple threads can access at the same time as read. However, if a thread wants to write, then this need to be exclusive. Now, I know that there are read/write locks designed specifically for this purpose. I would not do this...
I'm working on the floors of a building, using SVG objects generated by Raphael.js. All objects are clickable and all have different shapes, but all of them have the same actions. The code below is just a little sample. How could I optimize it? // FLOOR 00 var budA4_0 = new Raphael(document.getElementById('inter-b...
I used the following Javascript to sort an unnumbered list of numeric li-tags as follows: // 1. get the <UL>-element from the BODY var nList = document.getElementById("allItems"); // 2. extract all the <LI>-elements from that <UL> and put it in a NodeList var nEntry = nList.getElementsByTagName('li'); // 3. we can't s...
This code works, but I get the feeling that it could be shorter and simpler. Any ideas? private void CheckNameCase(Models.PersonalInformationModels.PersonalInformationModel model) { // if first middle and last names are all upper or lower case then title case the name //Name string firstName = model.NameM...
In a project I'm working on, the data access layer has evolved to something that somewhat resembles the Unit Of Work and Repository patterns, at least they started with those names, I'm not entirely sure with how far they've drifted, if they can still be called that. For classes data access, an implementation IWorkUnit...
I have this rather verbose piece of code. How can I get it shorter and simpler? This function aggregate results of test by population and by different keys: def aggregate(f): """ Aggregate population by several keys """ byMerchant = col.defaultdict(lambda: col.defaultdict(lambda: [0,0,0,0])) byPlat = col.de...
I've seen the pattern: <?php if ($node = node_load(30) && $node->type == 'bogus') { print $node->title . 'is bogus'; } But when I tried to use it I got a warning: variable not defined... Has this pattern of declaring variables while you loop in an if been deprecated?
I am getting information from an XML document and for the most part everything runs as it should. Occasionally, I get a php fatal error Call to a member function children() on a non-object. I have tried to use this if(isset($current->AttributeSets->children('ns2', true)->ItemAttributes->ListPrice->Amount)) { $listP...
In an attempt to learn more about Clojure's parallel computation functions, I devised the following task: calculate a factorial in parallel using pmap, pcalls and pvalues. The idea is to split the factorial sequence into sub-computations, reducing the final output of each. Here is the obvious non-parallel function: (d...
I'm a bit concerned about function usage. There are so many different libraries/possible ways to do something that I'm not sure if the way I'm working at the moment is reasonable, or what I could modify to have a better code. Also, I'm searching on how to optimize this code, since for a small 25MB file the memory use g...
I have the following Ruby code snippet: url = "http://somewiki.com/index.php?book=#{author}:#{title}&action=edit" encoded = URI.encode(url) encoded.gsub(/&/, "%26").sub(/%26action/, "&action") The last line is needed since I have to encode the ampersands (&) in the author and title but I need to leave the last o...
I'm in the process of building a website for the company I work for and I'm trying to think of the best way to namespace and organize the site's JavaScript code. I've written several jQuery/JavaScript plugins for the big chunks of code, but now I'd like a namespaced place to "call" said plugins and any other random Jav...
I have the following code in a portion of my program that hides/shows certain elements based on the status of a certain checkbox: private void enableFolderVariableRemoval_CheckedChanged(object sender, EventArgs e) { if (enableFolderVariableRemoval.Checked) { cleanFolderTextPanel.Visible = true; ...
To help learn the SharePoint object model (primarily for SharePoint 2007), I've been working on a class library with a number of useful functions. I'm a junior developer and this is my first C# project of this nature. With this in mind, how can I improve the class below? What bad habits do I have or what should I study...
I'm using this form to submit articles into the database: <form enctype="multipart/form-data" method="post" action="add.php"> <input name="title" type="text"> <input name="image" type="file"> <textarea name="text"></textarea> <input type="submit" name="go" value="Spremi"> </form> include ("database.php"); ...
I have a rather large class that needs to provide a reasonable amount of output for debugging purposes. I've done this with the following: #if DEBUG Console.WriteLine("Source Site Set to: {0}", archiveQueueEntity.SourceSite); Console.WriteLine("Source List Set to: {0}", archiveQueueEntity.SourceUrl); Console.WriteLine(...
I am using this code to insert and retrieve: namespace Gridwebpart.VisualWebPart1 { public partial class VisualWebPart1UserControl : UserControl { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { SPWeb site = SPContext.Current.Web...
I'm a developer at a networking company that really has no peers that work above me that I can use for any sort of sounding board for my code, so it's just me. I was wondering if anyone would be willing to take a look at some of my code and just give me a few notes, bullet points, etc... on things that are wrong, thin...
So I have a view model (asp.net mcv 3 app) that when instantiated with a particular parameter, populates it's properties via a couple of calls to a web service in it's constructor. public class QuizPreviewViewModel { private IQuizServiceWrapper _service; public string QuizName { get; set; } public List<Qu...
For logging purposes, I need to output a double[,] to the log file. So I need to represent the array as a string. The following code gets the job done using basic C# 1 features, but I was wondering if there is a more elegant solution using Linq: private static string OneRowPerLine(double[,] numbers) { var ret = new...
I am developing a webapp with Ruby on Rails to expand the features of mite (online time-tracking app) with the help of the offical mite API. Unfortuanaly, the API can't return all projects by a specific customer id. Because of that, i am developing a workaround. At first, i get all customers and save them in a hash. Th...
Also, how would I go about putting my class in another file? Thanks! #include <iostream> using std::cout; using std::endl; class Array { int *arrayPointer; public: Array(int size); ~Array(); int get(int index); void set(int index, int value); protected: int array[]; int size; }; Array::Array(int the...
How is this function? /// <summary>Extension methods used by RedViewerLibrary.</summary> internal static class Extensions { /// <summary>A string array extension method that gets the human readable enumerated version of the array.</summary> /// <param name="items">The strings to act on.</param> /// <returns...
I'm writing a library which calls a RESTful API and then performs some work on the data. I've architected my code like this: I have a class (let's call it APIRequestor) that initiates a call to the API via an injected HTTPRequestor library (which basically wraps a cURL request). That class, after retrieving the respons...
I have tables that use BulkManager to save data to database. I moved common functionality to BulkTableBase. Because creation of BulkManager depends on params of each Table I create the BulkManager in .ctor of the Table. The Add method of each Table is also different. But I feel that calling CreateBulkManager method in ...
I have a time-based signal (Raw signal) sampled at 6 MHz and need to analyze it in freq. domain. I'm learning DSP and this is very first time I work with DSP. Could you please help to check if this code is correct or not. And I have couple of questions needed to be clarify: I've heard about linear scale and logarithm...
I've written this code that I've been using for a while now to check for browser geolocation services for Google Maps applications. I have to say that I am not very happy with it as I've had to hack it quite a bit to work in IE9. Could I please get some critical assessment of the following and possible suggestions for ...
I implemented a MVC Framework with Generic DAO and I would like know if is correct. I did not have developed yet the MySQLDAO. My controller class class ClienteController { public function __construct() { } public function actionSubmit(){ $objCliente = new Cliente(); $objCliente->setNome($_POST['nome'...
I have files with over 100 million lines in each: ... 01-AUG-2012 02:29:44 important data 01-AUG-2012 02:29:44 important data 01-AUG-2012 02:36:02 important data some unimportant data blahblah (also unimportant data) some unimportant data 01-AUG-2012 02:40:15 important data some unimportant data ... As you can see, ...
import random from random import choice import os import time import texttable class Stack(): def __init__(self, replay, winnings): self.start_amount = 100 self.stored_bet = 0 self.stored_end = 0 self.replay = replay if self.replay == 0: self.stored_end = 0 #...
I am practicing using the Prototype pattern and to do so, I am building a simple CRUD app that allows me to view, add, and delete customers. Here is a JsFiddle for you to see what I've got so far. // Create customer 'class' and store state here var Customer = function(el) { this.el = document.getElementById(el); ...
I've written this code to convert an integer number into its word representation. I've tested it for many cases and it seems to be working as expected. For example: 1000 displayed as "One Thousand" 99999 displayed as "Ninety nine thousand nine hundred ninety nine" 999999999 displayed as "Nine hundred ninety nine milli...
I'm trying to build simple pattern matching in a string. ie., Given a template of: "Hello ${1}" and an input of "Hello world", I'd like to be able to return a map of 1='world'. This test demonstrates what I'm trying to acheive: @Test public void detectsTokenValues() { Properties properties = formatter.getTokenValue...
Here is my solution to reddit.com/r/dailyprogrammer #93 (easy)., which is a Python script that translates between English and Morse code. Is String_To_Translate a good example of a class? Am I violating convention? How can I improve this code and make it more readable and pythonic? import re morse_code_dict = { 'a':'....
I was wondering if anyone could give me a little bit of help with optimizing a tree-structure in C++. I'm currently developing a dictionary program for a school project but want to take it a bit further in my spare time. A little bit of info: The dictionary is a simple class which contains a node. Each node in the clas...
I made a function that returns the number displayed for pagination. I want to get something like this (parentheses is the only show where the active site): if pages < 10 1 2 3 4 5 6 7 8 9 10 if pages > 10 1 2 3 ... 20 [30] 40 ... 78 79 80 where [30] is active page. If active page < 3 1 2 [3] 4 ... 20 30 40 ... 78 79 ...
I have been working on a class to use Reflection to interrogate other PHP classes and interfaces, what I want to know from anyone with more experience of this is, is there anything else I can add, or is there a better way of doing the things I am trying to do. In essence I want to be able to use the interrogator to tel...
I began programming recently. I am trying to implement a simple trial-division algorithm for finding all primes up to some number (it is much more "primitive" algorithm than the Sieve of Eratosthenes). Can you please find what's wrong with my code? #range function: range = function (a,b,c){ var range1=[] for (...
I am doing my research about scheduling by using Matlab. I am a new Matlab user and I have a problem with time execution of my following code: clc clear all A=8; B=12; C=10; ProcessTime= [ 11 11 11 11 4 4 4 4 4 4 4 2 ]; %Converting Matrice RandomMatriceA=zeros(A,B,C); RandomMatriceB=zeros(A,B,C); SumRandomMatriceB=zer...
Just seeing if there is anyway to shorten these for statements? ... fillMonthSelect: function() { var month = new Date().getMonth() + 1; for (var i = 1; i <= 12; i++) { $('.card-expiry-month').append($('<option value="'+i+'" '+(month === i ? "selected" : "")+'>'+i+'</option>')); ...
I'm trying to implement a lexer in Haskell. For easy console input and output, I've used an intermediate data type Transition Table. type TransitionTable = [(Int, Transitions String Int)] type Transitions a b = [(a, b)] I want to take input from the user for all the states and transitions. I do not want to take the to...
For this exercise I have done this: func between(start, end, value byte) bool{ if value > end { return false } else if value < start { return false } return true } func (r rot13Reader) Read(p []byte) (n int, err error) { s, err := r.r.Read(p) if err != nil { return s, err...
I am animating 1400 objects trying to create a 'twinkling effect'. As the user moves the mouse faster more hexagon shapes pop into full opacity and have varying fade out rates. The version in the fiddle fills the space with enough color but feels jerky and clumpy. If I lessen the fade_time variable amounts it is smooth...
I created this very simple stack concept's implementation. Could you tell me if it is correct and clean? Do you see any bad coding habits? public class MyStack { private static final int MAXELEMENTS = 10; private int[] elements; private int numElements; public MyStack() { numElements = 0; ...
Can anyone help me prettify this code? The idea is to combine adjacent time spans so [0:00-1:00, 1:00-2:00, 3:00-4:00] becomes [0:00-2:00, 3:00-4:00] private static IEnumerable<Span> CombineAdjacentSpans(IEnumerable<Span> spans) { var combined = new List<Span>(); var list = spans.OrderBy(s => s.Start).ToList();...
I needed a boost.any look-a-like, that could handle a std::unique_ptr. I came up with this. Please provide some C++11 criticism. #ifndef ANY_HPP # define ANY_HPP #include <cassert> #include <stdexcept> #include <typeinfo> #include <type_traits> #include <utility> namespace generic { class any { public: any() ...
How can this be minimized? // remove accent byte[] bytes = System.Text.Encoding.UTF8.GetBytes(input); input = System.Text.Encoding.UTF8.GetString(bytes); // make it all lower case input = input.ToLower(); // remove stop words input = System.Text.RegularExpressions.Regex.Replace(input, "\\b" + string.Join("\\b|\\b", E...
I would like to know what is null test in java? How to rewrite the below code by avoiding null test. I was asked this question in an online test. I'll be grateful for any help offered. String mystere() throws IOException { InputStream input = null; try { input = new InputStream(new File("foo.txt"))...
I am working on a small serialization function which serializes form input to json. Here is the fiddle: http://jsfiddle.net/jdQfj/2/ I have currently no idea how to split up the array declarations let alone a combination of array and object declaration. However the function works good with infinite object nestings and ...
I am looking for a general review of my project here. I have written some Python, but not enough to feel confident in my ability to produce idiomatic code. #!/usr/bin/env python """mockjson.py: Library for mocking JSON objects from a template.""" __author__ = "James McMahon" __copyright__ = "Copyright 2012, James McM...
I'm developing a small website which is responsive, and I'm planning on displaying a number of items ( Demo ) on the page. As you can see in the link the items are displayed just fine, but what I'm trying to do is calculate the exact number of items that would fit inside the window ( more specific the actual space betw...
I know this is extremely trivial, but would you call the extension method below Remove or RemoveMany? Please provide justification. public static void Remove<TEntity>(this DbSet<TEntity> set, IEnumerable<TEntity> entities) where TEntity : class { foreach (var entity in entities) set.Remove(entity); } -...
I'd like a review of this implementation of Async in ASP.NET 2.0 web form page below. Let me know if I am missing something. AsyncPagesASPNET20.aspx <%@ Page Language="C#" Async="true" AutoEventWireup="true" CodeFile="AsyncPagesASPNET20.aspx.cs" Inherits="AsyncPagesASPNET20" %> AsyncPagesASPNET20.aspx.cs public parti...
I'm writing an API and want to be able to pass in the attributes of a model without prefixing them with the name of the model. I wrote this little extension to ActiveRecord in order to make it happen: module ActiveRecord class Base def self.filter_attributes(hash) hash.stringify_keys.slice(*self.accessible_...
I want an experienced Haskeller to critique my code and offer changes/suggestions (so I can learn the idioms of the language and culture around Haskell). I've been using a Tabula Recta for my passwords and used a Python script someone wrote to generate the table and do table traversal. I've been wanting to learn Haskel...
I have a Scala (Play!) application that must get and parse some data in JSON from an external service. I want to be able to gently handle failure in the response format, but it is becoming messy. What I am doing right now is, for instance, def columnsFor(json: JsValue): Option[Map[String, String]] = try { val col...
I have to create a website in Classic ASP, and I really want to do a clean design so I will try to put everything in Classes and Models to emulate the ViewModel Pattern. So can you tell me if this approach of creating objects is good because I will use it everywhere Class User Public Name Public Adress Publ...
I wrote this login method: [HttpPost] [ValidateAntiForgeryToken] public ActionResult Login(LoginModel logModel, string returnUrl) { if (!ModelState.IsValid) { TempData[Keys.ACCOUNT_TEMPDATA_LOGINSTATUS] = LoginStatus.InvalidCredentials; return RedirectToAction("L...
I wrote a program that generates a set of 1D cellular automaton. Basically, it generates this (rule 150): ...and rotates it to form this: I then introduced an element of randomness to it, so it could form images like this: I was hoping I could get reviews for the code I have, focusing around how to optimize it and i...
I just created this during a live screencast. The people who were on there were very critical of almost every line of code. They say I am a horrible coder and know nothing. Looking at this tax calculator, would you say I'm an OK coder? Demo I don't think they're right, but I require one or more objective subject-matte...
So I'm writing an abstraction layer that wraps a telephony RESTful service for sending text messages and making phone calls. I should build this in such a way that the low-level provider, in this case Twilio, can be easily swapped without having to re-code the higher level interactions. I'm using a package that is pre-...
I needed a class where I could store an instance of any type. The goal was an interface as follows: class TypeMap { template<typename T> T& get(); }; Such that: Iff &m1 == &m2 then &m1.get<T>() == &m2.get<T>(). The first call to m.get<T> for all m, T combinations returns a reference to a default-constructe...
This is the existing code. Clearly way too much is going on in this index method and furthermore it's untested (and hard to test in its current form). def index # @s = "" # @now=DateTime.now @from = params[:from]? ('01/01/'+params[:from]).to_date : '01/01/1991'.to_date @to = params[:to]? params[:to]+'/...
This is used to change a Cyrillic word with a stress marker into the same Cyrillic word but with the stress marker separately represented as a number. As I want to return two values I pass two parameters by reference. I assume there is at most only one stress marker per word. What could I improve here? function seperat...
(!empty($student->former_name) ? print $student->former_name : ''); I only want to print out the former name if it is not empty, nothing else. I imagine I do not need the else part of it, but I do not know how to do it like that without the else. I want to shorthand this: if(!empty($student->former_name)) print $stud...
I have just finished another page of my project and everything is working just great with the following code example. My first concern is whether you could recommend something to make my code look more beautiful or probably more secure? As I have no user input, I suppose this code can not be SQL injected? For connecti...
Here's my solution to Project Euler problem 40. import operator import math def levels(n): return 9 * n * 10 ** (n - 1) def face_value(i): def level_filler(i): n = 1 yield 1 while i > levels(n): yield int(levels(n)/n * 1.0) i -= levels(n) n += 1 ...
Very simple requirements here: connect to web service check if account number exists if it exists update it if it does not exist create the account I have accomplished this with the code below I am wondering if this is efficient and secondly if there is a better way of doing this. protected void Button1_Click(objec...