instruction
stringlengths
71
71.9k
This reads in data from a .csv file and generates an .xml file with respect to the .csv data. Can you spot any parts where re-factoring can make this code more efficient? import csv from xml.etree.ElementTree import Element, SubElement, Comment, tostring from xml.etree.ElementTree import ElementTree import xml.etree.El...
I have a very simple Pong game that I've built in Java. The code is quite long so I've decided to focus this question on the collision that occurs with the ball and the bat and also the effects in the game. I'm using ACM Graphics package to learn Java so most of the methods are from that package. I want to know how I c...
Something that has bugged me for a while, is what way is best to perform a conditional where a string is compared to other strings. Here is some sample code. This code is just for illustration purposes. The 3 methods I use are Do a word for word comparison. This is probably the most optimal, but ugliest code Creat...
Is it? And maybe theres a better way to do this? $allowed = array("name_desc", "name_asc", "level_desc", "level_asc", "vocation_desc", "vocation_asc"); $order = isset($_GET['order']) ? $_GET['order'] : "name"; $order = in_array($order, $allowed) ? str_replace("_", " ", $order) : "name"; $query = "SELECT * FROM player...
I've written a function for converting strings to upper case. It currently works by replacing each character using a Regex pattern with a hash: # Special upcase function that handles several Norwegian symbols. def norwegian_upcase(string) string.upcase.gsub(/[æøåäâãàáëêèéïîìíöôõòóüûùúý]/, { 'æ' => 'Æ', ...
I'm reviewing my code and trying to figure out how I can do some simplifying to flatten my code. Whether it be making simpler function out of the segment of code or by removing parts of it and wanted some opinions. if ($regenerated_post_password !== $user_data->password) { /* Password from login from does n...
You can check the problem here: http://projecteuler.net/problem=14 My first approach in Haskell was this: import Data.Ord import Data.List computeCollatzSequenceLength n = let compute l n | n == 1 = l+1 | even n = compute (l+1) (n `div` 2) | otherwise = compute (l+1) (3*n+1) in generate...
I would like some feedback on the code below. And how would I Implement pattern match on find users in role so that exact match not required? // MembershipProvider.FindUsersByName public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalReco...
I have this very simple problem : my code is too repetitive. It works, but it could be much cleaner. I don't know exactly where to start. I'd like to learn to work better, and I'd really like someone to help me with it. Here's the 2 bits of my code that are very repetitive (everything I've done myself) : $(document).r...
I have a data-structure class in C++ with an accessor to some object (may be large) and I have const and non-const methods using this accessor so I need to overload it. I am looking for a critique of the code below - maybe there is a way to accomplish the same thing that is cleaner? The way I understand it, there are t...
I recently asked this question about performance of an unordered_map, but I realize my question is probably more about this piece of code here. I create a 8 x 10 x 30 x 30 x 24000 nested vectors of floats. This structure is used to keep track of votes in this 5D space. Many of the bins are never actually incremented, t...
In my controller I had the idea to do something like the following: // retrieve fields from form $firstname = $form->getInput('firstname'); $lastname = $form->getInput('lastname'); [...] // create Member object $member = new Member($firstname, $lastname, [...]); // save Member in DB $this->_daoFactory->get('Member')->s...
I have a block of C# code here that stores data to an ArrayList from the database and compares each with the values from the GridView. Is there a way to reduce the line of code and improve its readability? while (DataReader.Read()) { arrHostName.Add(DataReader.GetString(0)); arrUsers.Add(DataReader.GetString(2...
I need to test performance of a function in PHP. This has to happen accurately, of course. In the end I need to know how long it takes for a function to perform. What I'm doing now: <?php $start = microtime(true); while (microtime(true) != $start + 1); // Wait a second to start up $loops = 10; $avg = 0; for ($i = 0; $...
I am an amateur programmer and I tried coding this problem using the TurboC++ IDE (though my code is in C), but the site's compiler throws a "TIME LIMIT EXCEEDED" error. How can I optimize my code further? #include<stdio.h> #include<math.h> int main() { long int n,j,k,sqt,tot,t,i,c; scanf("%ld",&t); for(i...
I am creating a C# service that will be doing some specialized processing of data coming into our ODS (Operational Data Store) DB. To support this, I’m building a DAL that will be used to access our ODS. In my DAL, I’ll have a number of GetItem (get a single item) and GetList (get a list of items) methods with a number...
Below you'll find a Symfony2 service I wrote to assist in handling the Library entity. Each user in my app has a personal library where one can upload items to and a purchased library, that contains items one has purchased. Both libraries fall under a parent library. At several points in my controller, I need to get th...
One of the servlet in my web app takes parameters in the form www.service.com/servletname/parameter1/parameter2. The first parameter is required and the second parameter is an integer. I've made some code to validate the parameters but it looks really really messy. Is there a nicer and cleaner way I can write the foll...
I found this code in our project and it just feels like the wrong way to do what it seems to be doing id<NSFastEnumeration> results = [info objectForKey: ZBarReaderControllerResults]; ZBarSymbol *symbol = nil; for (symbol in results) { // this just selects the first symbol in the results } Presumably it actually d...
I have to create a program in which t sets of m and n will be given by the user. For each set, we have to generate all prime numbers between m and n. This code is successfully executed with the correct output, but I have to reduce the time limit for a large data range. #include<math.h> #include<stdio.h> int isPrime(in...
This code parses a text file, replacing special tokens marked as $(token) with some replaced text. The $ symbol can be escaped by entering a double $$. In the example a user enters a text file containing tokens to replace and a separate mapping file with, for instance, colour:red to denote how to replace a token. Som...
I have recently started using Ruby and would like to hear your take on the following piece of code. class Generator def initialize @context = nil end def start(params) @context = Context.new params image = create_image if cache_update_request? upload image end return image end ...
I am writing web application using flask framework + mongodb. I have an issue, should I use classes for my mongo entities or just use dictionaries for them. class School: def __init__(self, num, addr, s_type): self.num = num self.addr = addr self.s_type = s_type or just create dictionary fo...
We know when we call HttpContext.Current.Response.Redirect("http://tvrowdy.in"); It throw an exception. Can we do it this way(working fine). Need suggestions and improvements. public static void ReferToPage(string strPageName) { try { HttpContext.Current.Response.Redirect(strPageName, false); } ...
Not so long ago I learned how to implement the minimax algorithm with alpha beta pruning, and even created a perfect Tic Tac Toe player. How can I improve this? public Best chooseMove(boolean side,int[]board,int alpha,int beta,int depth,int maxDepth){ Best myBest = new Best(); Best reply; int num; if...
I am building a 2d dictionary with an altered list at the end Afterwords I want to find the min of each list. Is there a better way to do it? Better being faster or at least less of an eyesore. #dummy function, will be replaced later so don't worry about it. def alter(x, y, z,): a = list(x) for i, val in enumer...
Okay, I'm under the impression that my current jQuery can be simplified (don't worry! It's short!) and I'm curious to know how this can be achieved. I think a solution to this will help produce a lot less code. I currently have a list menu set up, with class names referring to their titles (HTML below) and if you click...
I have written a java code to transfer files from one server to another using the concept of socket programming. Now, I also want to check for the network connection availability before each file is transferred. I also want that the files transferred should be transferred according to their numerical sequence, and whil...
I am currently working on a site where I have a bunch of tiles "fly in" to the screen. I need to add a class to each tile on a delay so they come in one after another. I have the following code that works, but if I want to add more tiles, I will have to edit the jQuery each time. Is there a way to trim this script do...
I'm having trouble structuring the logic of OAuth integration into my web app. In the app, a user creates a Report that consists of data from their Google Analytics account. User steps: User clicks 'New Report' Google presents the 'Allow Access' page for OAuth access User is presented with a list of their GA web prope...
The working and functional code below is a simplification of a real test application I've written. It acts as a client which asynchronously sends UDP data from a local endpoint and listens for an echo'ed response from a server implemented elsewhere. The requirements are: Send and listen on the same port number; The p...
I'll write a small simulation of my actual class first to request insights on unit testing one of the behaviors of this class. Here is my class A: public class A { private final String a; private final String b; private String c; public A(final String a, final String b) { this.a = a; this...
I'm creating a simple generic Map-wrapper with multiple keyed values. I'm intending to use it with storing edges in a graph, where an edge goes from one vertex to another. Thus, I can fetch any of the two vertices in constant time instead of having to loop to find either to/from. public class MultiMap<K1 extends Objec...
This may be a better fit for another board, but here goes: I've made a very simple gem that acts as a days-of-the-week bitmask. To be hip, I registered it on CodeClimate, where it's currently scoring a B/3.0 grade. Since there's only 1 extremely simple class, the B is bugging me. CodeClimate's reason is that there's to...
This code was first critiqued here (without the Card class): Card Deck class for a Poker game After learning more about data structures both online and in class, I wanted to revisit my Card and Deck classes and see if I can still make them better. Based on my driver tests, they are doing nearly everything I want them ...
I'm a newbie to javascript, and day after day, I try to write better code with jQuery. For example, I wrote this code earlier: $$foo= $(".foo"); $$foo.mouseenter(function() { $(this).find('h1').addClass("hover"); }); $$foo.mouseleave(function() { $("h1").removeClass("hover"); }); What I want to happen with t...
I am just beginning to dabble in C++. Would you implement this as a class like I did, or a struct? What are the pros and cons? class Point { private: double _x; double _y; public: Point(); Point(double x, double y); ~Point(); Point(Point& other); double GetX(); void SetX...
I built a simple PHP spellchecker and suggestions app that uses PHP's similar_text() and levenshtein() functions to compare words from a dictionary that is loaded into an array. How it works is first I load the contents of the dictionary into an array. I split the user's input into words and spell check each of the wo...
I want to implement in my code a cache mechanism with a fixed duration. For example an iframe will be cached for one hour, or a script file will be cached for 24 hours. This is how I implemented it, with a rounded timestamp (simplified code assuming that the url doesn't have any query or hash part): var duration=864000...
I think I'd like to learn Clojure eventually, but at the moment am having fun with Hy, a "dialect of Lisp that's embedded in Python." (import socket) (defn echo-upper (sock) (.send c (.upper (.recv c 10000))) (.close c) ) (def s socket.socket) (.bind s (tuple ["" 8000])) (.listen s 5) (while True (echo-upper (...
My program will fork, launching $n children. When a child finishes, the parent will launch a new one, if we have more to launch. #!/usr/bin/perl use strict; use warnings; use POSIX ":sys_wait_h"; #function, that every child will run sub func # {{{ { my $i = shift; my $delay = shift; print "$i start...
I'm new to SQLite but have programmed in BASIC (and other languages) for pushing 50 years. Given the sample code extract, please offer suggestions for improvement: Sub addAuthor(ByVal authorlnf As String, ByVal authorfnf As String) Dim objConn As SQLiteConnection Dim objCommand As SQLiteCommand ...
I've building a multi-step form that saves data in multiple models. The "base" or parent model is the Venue, and has_one or has_many other models. In the screen below, the "Basic Information" tab is the only one which is mandatory to fill. Once that is saved, a row is generated in the Venue table in the database, and t...
I am fairly new at writing jQuery plugins. Moreover, I am a huge fan of best practice. I have written a plugin which centers an element inside its parent. I would love some feedback on how I could have written it better. (function( $ ){ $.fn.verticalCenter = function(options) { var settings = $.extend({ ...
I am currently writing a simple PHP script that uses themes and I found myself writing these methods as part of a class that handles theme config files: public function getArrayOfThemeNames() { $this->loadUnfilteredDirectoryListing(); $this->loadThemeFiles(); return $this->theme_files; } private function l...
I have recently written the following Pong game in Java: Pong class: import java.awt.Color; import javax.swing.JFrame; public class Pong extends JFrame { private final static int WIDTH = 700, HEIGHT = 450; private PongPanel panel; public Pong() { setSize(WIDTH, HEIGHT); setTitle("Pong"); ...
I've created this script and I want to use it for website navigation in my project. As my knowledge of jQuery is quite poor, I'm not sure that code is correct and enough optimized. Could you help me to find out if there are any ways to optimize the code, and indicate mistakes I've made? $(function () { //scroll to the ...
I'm trying to learn learning javascript and jQuery plugin standards, and after some googling and testing I've come up with this pattern: ;(function(window, document, $, undefined){ var plugin = function(element){ var instance = this, somePrivateFunc = function(){ console.log(instance.options); ...
There are 10 threads and I have 15 tasks. Now I have submitted all these tasks to these threads. I need to write all these threads output to a file which I was not successful. I am getting output by running all the threads. ThreadPool.java (Creates a Thread pool and adds all the tasks to the Blocking queue and submits)...
I am trying to start learning Python using Learn Python the Hard Way. I wrote my first game that works as far as tested. It was done as an exercise for this. Please give me some constructive criticism on this program on sections and areas where I can improve. I realise that my object-oriented programming specifically, ...
TL;DR I need a way to refactor a complex user dashboard with several objects and some complex data to display a accounting chart. I have read about both presenters (also called decorators or view models) and service object, but I'm not sure if I should use one or the other, or both? And how to implement this? My model ...
This is my first real attempt at a Scala program. I come from a predominantly Java background, so I'd like to know if the program sticks to Scala conventions well. Is it well readable or should it be formulated differently? To me, there is a lot of lines in the main function which doesn't quite bode right. It is func...
I've been studying compiler construction theory. Right now, I'm studying Finite State Automaton and I've tried to create my own implementation. I'm not sure if my implementation is right. <?php /** * FINITE STATE AUTOMATON * ====================== * - states * - starting state * - accept state * - transition tab...
A small struct is sent beforehand to the client that specifies package_size amount of data should be received which is what p->data_value_1 contains. Server side: void Server::sendDataSingleUser(char *data_in, int user, unsigned int package_size){ package_size_sent_ = 0; FD_ZERO(&write_set_); FD_SET(sockets...
I have recently gotten into Java in a Computer Science class at my high school and I am trying to learn more than just the basics I have learned in school. Yesterday, I designed a very simple text editor I named Aqua that is written with Swing. For some reason, my computer drags a little bit when I run these methods. I...
I'm going to be working on a much larger version of this program and I just wanted to see if there was anything I should change in my style of coding before I made anything larger. If it wasn't obvious, this code goes through each comic on A Softer World and downloads each comic. Oh and with larger projects, should I t...
I'm trying to write a multi-threaded utility that logs some audit trails to the DB every 30 minutes, or whenever my storage data structure (a list in this case) exceeds a certain limit. The code works well, but having said that, my manager said there could potentially be some issues in the method LogUserUsageData(...) ...
I am learning JavaScript and I just wrote a Rock, Paper, Scissors game that will first prompt the two players for their choices and validate them. In the event of a tie, each player will choose their answer again and it will once again be validated. Everything works fine, but it feels like I have a lot of repetition go...
Basically I have a function of the type 'a -> 'a (an optimization function on a AST) and I want to call it (passing the previous result) until it returns the same thing as the input. Right now I have this: let performOptimizations ast = Seq.initInfinite (fun _ -> 0) |> Seq.scan (fun last _ -> optimizeAst last) ast...
I've created this adjacency list, but I don't like the design of the graph. The issue is that there is one pointer in the node to its adjacency list and there is a pointer in an adj_list node to the actual node. I am also using next pointers to traverse the graph in the order in which nodes were added and the list to g...
I have the following ajax call: function getPreviewText() { $.ajax({ type: 'POST', url: '@Url.Action("PreviewWiki")', dataType: 'json', data: 'source=' + $('#markItUp').val(), success: function (data) { $('#previewMode').html(data.RenderedSource); } })...
I'm learning ASP.NET and think I figured out ViewState. Can you tell me if I have it right? The goal of the ViewState in this page is simply to keep the value in a DropDownList. So first, let's have the aspx page markup: <%@ Page Title="Parameters" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" Cod...
I recently learned Haskell, and I am trying to apply it to the code I use in order to get a feeling for the language. I really like the Repa library since I manipulate a lot of multi-dimensional data. Yet it is, in my sense, missing a lot of signal processing tools. For instance, I use quite a lot of Gaussian filter co...
I'm refactoring a responsive report builder in JavaScript. Here's what it looks like: This started as a small set of objects that transformed data, rendered the graphs with D3.js, and managed the layout all in the same object. The graphs can be removed by the user, and they resize based on screen width and the layout ...
I have two class: InputForm.java public class InputForm { private String brandCode; private String caution; public String getBrandCode() { return brandCode; } public void setBrandCode(String brandCode) { this.brandCode = brandCode; } public String getCaution() { re...
In my current project, I am working with a lot of JSON objects that contain arrays, er.. lists so I setup a decorator for convienece when the list is one item or multiple. Even though this is convienent in the current project, is it reusable code? def collapse(function): @functools.wraps(function) def func(*arg...
I have made the following custom defined function in Excel. It works somehow like VLOOKUP(), but it takes two criteria. I think the code is a bit of a mess. Does anyone has any comments, suggestions, or improvements? Public Function VLOOKUPMC(ByVal return_col_num As Long, ByRef table_array_1 As Range, ByVal lookup_valu...
Declare @IsExistRoleAR As bit Declare @IsExistRoleEN As bit Declare @IsExist AS bit set @IsExistRoleAR=(SELECT CASE WHEN COUNT(RoleID) > 0 THEN 1 ELSE 0 END AS isExists FROM Roles WHERE RoleDescAR='Arabic Name') set @IsExistRoleEN=(SELECT CASE WHEN COUNT(RoleID) > 0 THEN 1 ELSE...
I made the code, and it works, but it uses many if conditions and it looks ugly. I would really appreciate it if someone could give me a hand by pointing me in the right direction to make it more object-oriented. package ar.edu.uca.ceis.objetos.imperio; import ar.uba.fi.algo3.batallaespacial.CabinaDeControl; import a...
I have a program which is primarily illustrative in example to help me learn refactoring techniques and best practices. This program will take the ActiveTabIndex property of a TabContainer control and add a GridView control to the page and bind it to a database using a stored procedure. Each tab in the TabContainer w...
I have implemented a WaitGroup class to simulate WaitGroup in Go lang. Then I've found that I can use Barrier in a different manner, to achieve the same thing. My WaitGroup has some additional functionality, but in most scenarios Barrier just would do. Question: Do you spot any design flaws in this style of using Barri...
OK, this question may seem a little strange at first; however I'd like to have your comments on it. Background: I do Java. A lot. Java is a statically typed language, it has means to restrict visibility of instance variables, etc. And as such the builder pattern (see here) is quite adapted to it. I took this pattern a ...
I'm converting some C# code to F#. Basically it is some geometry classes that can have properties tuned by a numerical solver. I start with a discriminated union of type parameter that can be fixed or free ( tunable ) and then build tunable geometry objects out of them. I create a discriminated union called shape with ...
I need to concatenate two content_tag and it works but it seems a little messy to me. Any thoughts on how may I refactor this? def format_price(money) mny = get_price_string(money).to_money str = content_tag(:span, @visitor.currency.symbol.html_safe, class: 'pounds') str << mny.format(no_cents: true, symbol: '') ...
I'm working on a school assignment, and it's working fine, but I have a feeling I'm over-using pointers, and I just can't think of a way to not pass a triple pointer to the function readFile. I'd be more than grateful for your suggestions, and if you have any other suggestions on how to improve my code I'd be glad to h...
I've began to read the book Clean Code by Robert Martin, I had a strong desire to learn how to write code that's easy for others to understand. Please criticize my code. PuzzlesView.java // Using of PuzzlesView: // dimension = new Dimension(rows, columns) // puzzlesView.set(bitmap, dimension); // after the setting the ...
Could you please help me to review my first function (modified from an example) in terms of best practice, coding style suggestions and any obvious language mistake/improvements? unsigned int edit_distance(const vector<string> &s1, const vector<string> &s2) { const size_t len1 = s1.size(), len2 = s2.size(); vec...
I have crated the following small script. I just need to improve this complicated code if possible. def convUnixTime(t): expr_date = int(t) * 86400 fmt = '%Y-%m-%d %H:%M:%S' d1 = datetime.date.today().strftime('%Y-%m-%d %H:%M:%S') d2 = datetime.datetime.fromtimestamp(int(expr_date)).strftime('%Y-%m-%d ...
Is this the correct implementation of a singleton using enum? public class Item3 { public static void main(String[] args) { Singleton s=Singleton.Single.INSTANCE.getInstance(); Singleton s2=Singleton.Single.INSTANCE.getInstance(); System.out.printf("%b",s==s2); } } class Singleton { enum Single{ ...
I want a good design to implement a master-slave protocol. The protocol is proprietary and similar to cctalk. We have: Master: HEADER [ DATA ] CHECKSUM Slave: HEADER [ DATA ] CHECKSUM My choice was to have concrete base classes for request and for response: class PacketReq { public: typedef std::vector<uint8_t> ...
Any time I'm testing a Ruby class that calls a Kernel method such as sleep or exit, i define a singleton method on the class instance and test that it has been invoked: it "must throttle requests" do sleep_was_called = false subject.define_singleton_method(:sleep) { |seconds| sleep_was_called = true } sub...
I need to find the flaws in this design. So far the only ones i can think of are: No use of generics the class Concept uses a parametrized constructor, which means every sub class would need to pass a parameter. The setter method could be used instead. Can you think of anymore flaws? Concept.Java public...
I'm new to Elixir, and in order to learn the syntax, I'm doing a roman numeral kata which converts a decimal number into roman numeral. I would appreciate any feedback you have. defmodule RomanNumeral do @decimal_roman_numerals [[5, 'V'], [4, 'IV'], [1, 'I']] def converts(number) do converts(number, [], @deci...
I am working on a Java program which creates a map using Voronoi. I am using a Java library which generates Voronoi and it is very fast. The problem I am facing is that, then, I have to scan every Voronoi edge to know what point is on the left and on the right of the edge to create the polygon which contains each point...
This is DFS/BFS C++ code for Cormen pseudo code. Please comment on this. #include "iostream" #include "vector" #include "list" enum color{ WHITE, GREY, BLACK }; struct edge{ int destination_vertex; edge(int ver){ destination_vertex = ver; } }; struct vertex{ int id; color visi...
I hate having almost two identical blocks do almost the exact same thing. I am working with Entity Framework 4.4.0.0 Asp.Net MVC Right now if the user is a "manager" I want to show them the entire list, if they are a normal user or a Team Lead. I only want to show them their specific department. The only different fr...
Basically, the code converts a large select list with optgroups into a more user-friendly tabbed Twitter-bootstrap component. I'm not sure how much into detail I need to get but on GitHub I uploaded a working example. This is the first time I write a jquery plugin and any advise is welcome. (function($) { $.fn.boot...
So I have a DataTable that returns results within a month to month range when available. However, when I format the return, I need to still show skipped months as blanks. I have a working solution, but it's a little verbose and I think it can be done cleaner. Here's a setup to the problem Dim startMonth As Date = #5/1...
Ok, So first I must say that everything I know about coding I have learned on my own in my spare time so bear with me if my code is primitive, but please, I am open to any comments to make me better... Anyway, as for my question. I have an application I am building in C# for .NET Compact Framework (for an HP iPaq) the ...
I'm trying to reduce consecutive elements of array to one, but not for all values like: {3,0,0,0,3,3,3,0,0,0} => {3,0,3,0} but for specific one, in my example 0: {3,0,0,0,3,3,3,0,0,0} => {3,0,3,3,3,0} so only zeros (the threes are intact) are reduced. I have Java String working code I wrote: public static String remo...
This algorithm is intended to determine the epsilon of a given double precision number. As numbers increase in value, their accuracy decreases. This algorithm will return the smallest increment / decrement possible at any given value. Given the way floating point numbers are structured, is there logically any situation...
I am basically looking for Critique on the following code as i know its not the best and i am trying to find a set way of building javascript objects. Be brutal as you way its a learning tool for me, basically i am pulling in a twitter feed via json and adding it to the dom. var TwitterTimeline = { twitterFeed: funct...
Just checking that this shuffling algorithm is suitable. Or maybe there could be improvements? public static void shuffleArray(Object[] arr, Random rnd){ int lastIndex = arr.length - 1; for (int i=0; i<=lastIndex; i++){ int k = nextInt(i,lastIndex+1, rnd); Object a = arr[i]; Object b = a...
Edit: Disclaimer: I am new to templates and traits. I apologize in advance if this is a bad question. I am refactoring two similar classes with small differences strewn all over them into one template class (or I am trying to anyway). This is something I just wrote. (I hope I didn't make any mistakes renaming everythin...
I am attempting to write a function to calculate a user's Chinese zodiac sign based on his or her birthday for Drupal. I originally had a function for calculating based on the Gregorian calendar (1924 = Rat, 1925 = Ox). This was easy to write, but several of my users have complained that the Chinese zodiac is actually...
Each element of the array is a coordinate (x, y). Each coordinate has two labels. Goal: sum the elements that have the same two labels. How can this be made faster? import numpy from scipy import ndimage label1 = numpy.array([0, 0, 1, 1, 2, 2]) kinds_of_label1 = 3 label2 = numpy.array([0, 1, 0, 0, 1, 1]) ki...
I just want to know if there room for improvement or something I should redo to be better. var dataCell = new Array(); dataCell[0] = document.getElementById("data0"); dataCell[1] = document.getElementById("data1"); dataCell[2] = document.getElementById("data2"); dataCell[3] = document.getElementById("da...
While solving a problem on an online judge, I tried with these two implementations. These two implementations do the same thing. Task is to report duplicate entry for a given set of data. Implementation #1 : Converts input data to a String and adds to a HashSet. After all the input is read, appropriate message is displ...
I am working on a way to parse data using xml. The file that I am given contains lines that look like this: George | Washington | Carver or someone else can send me someting like this Carver | Washington | George And so on... No matter what the format is, whoever sends me the file will also send me rules on how to ...
I'm working on a CMS, currently on being able to create static pages, manage menus etc. so.. I have This function that reads from the DB and finds all the static pages, and their position in the menu. I want to know what Do you think. function update_menu(&$pdo, $filepath){ $qry = "SELECT * FROM pages WHERE top = 1"; ...