instruction stringlengths 71 71.9k |
|---|
I have made a simple MVC framework of my own for my personal website to learn a thing or two about how this whole thing even works. I think I've got the idea, but there's one thing I'm not sure about.
Now I know that a model shouldn't need anything specific - everything has to be generalized so it's accessible from mul... |
I am currently using this to convert a List of booleans to a string
var tempbllist = new List<int>();
foreach (var t in blenabled)
switch (t)
{
case true:
tempbllist.Add(1);
break;
case false:
... |
This code works, and I'm trying to figure out if there's a better way to optimize it. As you can see, I've cut down drastically on time just by using numbers that work for a < b < c. Is there any outstanding thing that can reduce the time? It currently takes ~7 seconds.
Problem:
A Pythagorean triplet is a set of three... |
I have some values pulled from a web service giving me a bool value for a key. I did it this way, but feel like it is repeating without need. How can I refactor this?
Please note that the key on the dictionary has the same name as the object property.
for (NSDictionary *itemDicto in switchesArray) {
if ([[itemDic... |
I have a basic CRUD DAO using JDBC to access my database. I using a connection pool to get a connection in each method and then execute my commands. In some scenarios for update User, there might be cases where I don't have to update the whole DTO to the database. In my insert and my findbykey() methods, I found out q... |
I have been working with Lua lately and I have discovered that it is capable of doing some very interesting things. I have created a proof of concept that allows one Lua script to load another Lua script and use the loaded script to modify itself by passing itself as an argument to the creation function of the loaded s... |
Find ceiling and floor in the BinarySearchTree. Looking for code-review, optmizations and best practices.
public class FloorCeiling {
private TreeNode root;
public FloorCeiling(List<Integer> items) {
create(items);
}
private void create (List<Integer> items) {
if (items.isEmpty()) ... |
I've implemented the trapezoidal rule to compute the integral for a function \$x^2\$. I would like to see another style of the same code. It seems Matlab hates for a matrix to be expanded without specifying the size.
clear all
clc
n = 5; % number subdivisions
a = 1.0; % lower limit
b = 2.0; % upper limit
sum = 0.0;... |
The code below implements a brute force method to find an energy optimal path for a given amount of time t_aim using recursion (the recursion function is optimalPath).
It seems the code works as expected. The transition energy and time is provided by transEnergy and transTime. v_tmp holds indices to the found transitio... |
I am currently setting over a hundred global variables by performing individual checks against the URL string.
var Query_MenuTiles = getParameterByName("menutiles")
var Query_Link = getParameterByName("link")
var Query_Speed = getParameterByName("speed")
Unless it would slow things down, I assume that setting keys and... |
Throughout my code, I find myself testing if the output of a function is undefined or blank before i use the output. In this case, getQuery checks if the property of an object is either blank or if the object key is not set at all. In both cases, the output can be ignored. But if the object key holds a value, then I wa... |
I have a repository called PostsRepository who implements an interface called IPostsRepository:
public interface IPostsRepository
{
IEnumerable<Post> All();
}
public class PostsRepository : IPostsRepository
{
private readonly DatabaseContext context;
public PostsRepository(DatabaseContext context)
{
... |
I am working on a personal project where I analyse Big Data by using twitter statuses. Therefore I am trying to query the Twitter API as many times as I can.
The API has a limit of 180 queries per 15 minutes, so I figured I can do 1 query every 5 seconds (at the minimum) if I want to not exceed that limit.
In the code ... |
The if/else statements below are not good. How can I improve this method?
public T GetContentByNodeIdSync<T>(Guid nodeId)
{
var data = m_CMSCatalog.GetContentByNodeId(nodeId);
if (typeof(T) == typeof(WebFolder))
{
var model = (WebFolderDTO)data;
return Mapper.Map<WebFolderDTO, T>(model);
... |
I am adding some check box filters on a HTML table, based on whether a check box is checked or not, and I am toggling rows. Is there anyway I could improve this code? There is no issue with it at the moment I could think of e.g. performance wise, but maybe someone could help me with decreasing number of lines.
HTML
<... |
I've written a simple Simple Service Discovery Protocol (SSDP) module. This module contains a class, Session that you create and then use to issue commands and subscribe to interesting events. I include the relevant code snippets below, but you can also view the entire SSDP module gist.
The usage looks like this:
//F... |
I am making a Cryptography application and I noticed that the encrypted file is approximately 2 times bigger because I am encoding the files in base64. Are there any file encodings that take less space? Here is the code that converts files into byte arrays:
Console.Write("Enter File Path: ");
docPath = Console.ReadLine... |
This is where I got the idea for most of the code.
I think this is pretty decent. I want this reviewed for security. Any criticism is welcome.
<?php
require_once('db.php');
//Create new Authentication Class
class Auth{
//Single underscore indicates variable privacy
private $_siteKey;
private $_dbh;
/*... |
I have a function that loops through large objects of raw data, translating coded strings into readable words. The function is very basic, and I keep wondering if I should use an object instead containing the words to be detected and translated. This would be cleaner-looking and more flexible, but it would not like it ... |
I have attempted to create an internationalization system for my PHP framework that I'm working on.
For the purpose I decided I will be using MySQL to store languages and translations. Respectively I have the tables
languages
id | name
----+--------
1 | English
2 | Spanish
translations
id | 1 | 2 ... |
I've implemented a simple C++ STL like queue. (I've tried to follow @LokiAstari stack implementation code fashion)
#ifndef QUEUE_H
#define QUEUE_H
#include <iostream>
#include <stdexcept>
using std::cout;
template <typename T>
class queue {
public:
struct node {
T data;
node *next;
node(... |
I am making an application to check for any files that does not follow a specific pattern defined in a XML file. The application works well, but the source code is not the greatest, and memory management might slow things down a little.
So I'm asking for a review of my code and to especially give me some general tips a... |
I have a situation where I'm generating a URL based on a set of query string parameters for use in an API. I know ahead of time that the values passed to this function are URL-safe and the tuples are complete, so I don't need to serialize the data or do data validation beyond just checking the length of the array.
This... |
I'm trying to solve the project Euler problem 54.
In the card game poker, a hand consists of five cards and are ranked, from lowest to highest, in the following way:
High Card: Highest value card.
One Pair: Two cards of the same value.
Two Pairs: Two different pairs.
Three of a Kind: Three cards of the same value.
S... |
I'm new to ruby. Recently I wrote a script to add a credentialsID node to each SVN location node in each config.xml file for all of our Jenkins jobs (We have many).
It works, but I'm guessing it could be done more elegantly. How would you fix this to be more succinct, clean, etc.
require 'nokogiri'
Dir["somepathhere/.... |
I want to create algebra evaluator but I don't want to write my own parser because it takes much time to learn.
I don't like algebra expression in C# because it does not look natural compared to VB counterpart. For example, "x^2+1" in VB must be written as "Math.Pow(x,2)+1" in C#.
I am still a newbie in the world of p... |
I am developing my social network website, and I want to know if it's optimized or not. I am good at ASP.NET 4 and WebForms, but not MVC or JavaScript.
This code is for "liking" a post. I did not use any JavaScript to do that. Is this "like" button optimized or not? How many online users can my server handle (assum... |
I created a simple program that downloads an image (different image every day), then sets it as my desktop background. I feel like the lines of code can be cut down significantly while still remaining easy to understand.
It is a console application, and closes immediately after downloading the image and setting it as m... |
I'm pretty new to MVC. Below is the code that I have added to an existing MVC 5 application. The code is using log4net to log any run-time error/exception.
NOTE: I could override OnException() in MVC filter "HandleErrorAttribute" but I preferred to have this functionality in my custom Controller base class.
Can anyone... |
Problem statement:
Input is a rectangular bitmap like this:
0001
0011
0110
The task is to find for each black (0) "pixel", the distance to the
closest white (1) "pixel". So, the output to the above should be:
3 2 1 0
2 1 0 0
1 0 0 1
Below is a working, heavily-commented 78-lines solution. It is very naive, thoug... |
I'm attempting to provide an agnostic means of identifying a member. I need a nickname, a guid, and one of user_id, email, or phone_number. Since I'm using Python, I try to not care about the Python type of member because, after all, if it has what I'm looking for then I don't really care whether it really is a Member.... |
I'm learning about SRP and had to reduce the responsibility of a customer object, which contained too much info. So I turned that into just a Pojo and pulled out the database logic.
I'm trying to find the best design for this setup and am split between making the DatabaseManager class be a parent class, or a singleton... |
Given a binary tree and a positive integer \$k\$, print all nodes that
are distance \$k\$ from a leaf node.
Here, the meaning of distance is different from the previous post.
Here, \$k\$ is the distance from a leaf means \$k\$ levels higher than
a leaf node. For example, if \$k\$ is more than height of binary tr... |
I think I'm on the right track, but ANY suggestions or critques are welcome. The program just scrapes an HTML table and prints it to stdout.
import sys
from urllib2 import urlopen, URLError
from argparse import ArgumentParser
from bs4 import BeautifulSoup
def parse_arguments():
""" Process command line arguments... |
I want to implement basic audio functions like play, stop and pause. I have stuffed all the code inside onCreate method. Is this best practise to follow?
public class MainActivity extends Activity {
Button start,pause,stop;
@Override
protected void onCreate(Bundle savedInstanceState) {
... |
I developed a lot of code locally with __uint128_t only to find out that it is not available on the target platform.
I am now trying to write my own struct that emulates the operators of __uint128_t I need: =, ~, ^, &, |, ^=, &=, |=
This is the code I have now, which will be compiled with a C++11 compiler:
struct board... |
I want to open a file contents using swing. For this I used the SwingWorker class. This application took more time (more than a minute) to load a large file (nearly 40MB). I want to improve the performance of the open file contents.
public class OpenDemo extends javax.swing.JFrame {
JTextPane textPane;
JScrollPane sc... |
I have written some code using RESTEasy to handle RESTful service calls and parse the response XML into relevant JAXB annotated classes. At the moment I have seperate methods for each return type:
public class RestBase {
protected final RestClient restClient;
public RestBase() {
restClient = RestManage... |
I've a Linq query that performs poorly:
var minuteValues = ValuesInMemory.Where(o => o.Key.Day == tmpValue.QuoteDate.Day &&
o.Key.Hour == tmpValue.QuoteDate.Hour &&
o.Key.Minute == tmpValue.QuoteDate.Minute &&
o.Key.Se... |
I've just wrote this class for an image slider (it cross-fades rather than sliding, so a class rename may be beneficial). It's my first proper attempt at JavaScript OOP. Can anyone see any real issues with this?
// Wrapper is the container element, in this case $('#sliderWrap').
// images is an array of the images.
fu... |
In essence, I need to do a stable partition: All elements of the 1D np.array a that are present in b should be moved to the front of a but apart from that, the relative order of the elements in a should be preserved.
This code seems to do what I want:
from __future__ import print_function
import numpy as np
if __name_... |
I attempted to write a AVL Tree in a functional style and I am hoping to get it reviewed. I am looking for the code to be clear and concise, any opportunity for improvement would be greatly appreciated!
This is the general binary tree class. I just left the insertion portion in the class to keep it easier to look at:
... |
I have this huge __init__ method which I want to clean up even more after watching Clean Coders videos (content of Clean Code book by Robert Cecil Martin).
How could I get refactor the gigantic if..elif block in a nice, readable way? Or should I leave it as it is? Do you find it readable?
@total_ordering
class Range:
... |
I needed a way of attaching multiple repositories to a presenter. Given I already had an IRepository abstraction, coming up with an IUnitOfWork seemed the next logical step.
The UoW opens a connection upon being created and, since it's a unit of work, initiates a transaction. Because I wanted the client code to be able... |
Our application needed a function to sign out of Google. Unfortunately, there is no such API and I was forced to use an iframe to: http://accounts.google.com/Logout and a polling mechanism to see when the operation is complete.
I had a lot of doubts whether to put this code in a directive or in a service.
On one hand ... |
The inspiration for this question comes from a talk by IanCooper; in particular, this remark:
Never mock somebody else's interface... you want to mock your abstraction of how you call the third party
I'm implementing a monitor for our hadoop cluster; something that examines TaskCompletionEvents and exposes certain cl... |
I often find myself abusing dictionary objects just for the exist method like this,
For Each x in Something
If Not dict.Exists(x) Then dict.Add x, False
Next x
Then just exploit the .Exists(x) method. It happens often enough that I thought it merited it's own class.
Instead of composing Scripting.Dictionary, I d... |
The code is not for any project, I just want to know the best coding practices. The code is also on GitHub.
#include <iostream>
#include <new>
#include <typeinfo>
using namespace std;
/****************************************************************
* Exceptions
****************************************************... |
I've created an algorithm which weighs the relevance of a list of articles against two lists of keywords that correlate to attributes of the article.
It works great and is super efficient... but it's a mess. It's not terribly readable, so it's difficult to discern what's going.
The operation in pseudo code goes somethi... |
I made a SwingWorker which is fetching tweets using the twitter4j API.
The twitter API will allow 180 queries every 15 minutes, and then throw an exception with code 88 which says that the rate limit was reached. My worker is initiated from a toggle button, if the button is selected and no other worker is running (not... |
I've heard of this implementation of quick sort (in pseudocode):
TAIL-RECURSIVE-QUICKSORT(A, p, r)
while p < r
q = PARTITION(A, p, r)
if q < (p + (r-p)/2)
TAIL-RECURSIVE-QUICKSORT(A, p, q-1)
p = q+1
else
TAIL-RECURSIVE-QUICKSORT(A, q+1, p)
r = q-1
Here it is partially i... |
A Magic Fraction for N is one that has the following properties:
It is a proper fraction (the value is < 1)
It cannot be reduced further (the GCD of the numerator and the denominator is 1)
The product of the numerator and the denominator is factorial of N. i.e. if a/b is the fraction, then a*b = N!
Examples of Magic... |
This function has a set of radio inputs, for each radio there is a hidden text input. When a radio input is checked it shows its chained text input.
I've done it with a function constructor, and I could have done this with closures or with simpler invocation patterns. My idea is to have some robust function which I cou... |
I'm writing an app to let me interact and debug my android over USB using the android SDK and the ADB command. I create a Process with redirected input and output streams and basically run "ADB shell", and I want to be able to wait for the prompt, enter commands and parse the results.
Here's a sample running ps and ge... |
Please review my code:
import java.lang.*;
import java.util.*;
import java.io.*;
class NumberToWords
{
static public boolean HelperConvertNumberToText(int num, String[] result)
{
String [] strones = {
"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight",
"Nine", "Ten", "Eleven", "T... |
I wrote this short subroutine to left, center, right-align a multiline string.
How can I make it better (shorter, prettier, optimized)? Can you offer some suggestions?
#!/usr/bin/env perl
use strict;
# A bit of text
$_ = <<END;
Lorem ipsum dolor sit amet consectetur adipiscing elit
Curabitur pretium o... |
This code simply returns a small section of HTML code and then gets rid of all tags except for break tags.
It seems inefficient because you cannot search and replace with a beautiful soup object as you can with a Python string, so I was forced to switch it back and forth from a beautiful soup object to a string several... |
I have created Tic Tac Toe game using plain JavaScript. Can any javascript expert review it and let me know whether the way I have written JavaScript code that is right (preferable)?
I am unsure that I wrote the OnLoad function in a preferable way. I wanted wrap all my code in an immediate invoking function but that di... |
I've been working for a while on a decision theory library, and since I've never really had any formal training in code best practices I'd love to hear your feedback. This particular class is one of my older ones, and it performs the Value Iteration algorithm on a supplied class which respects a particular interface.
... |
I figured working through Project Euler problems in Swift would be a good way to learn any tips or tricks. For example, tuples are something I'm not used to using, but they proved useful here. Using things makes me more confident with them, so perhaps this will help me find other uses for them in the future.
Each ne... |
The function days_name receive a val (string) corresponding to weekdays in hexadecimal.
def days_name(val)
value = val.to_i(16)
week = Array.new
if value.eql? 127
week.push 'All'
elsif value.eql? 0
week.push 'No'
else
week.push 'mon' if (value & 1) > 0
week.push 'tue' if (v... |
To avoid the XY problem, here is an example of what I need. Given the sorted integer input array
[1 1 1 2 2 3], I would like to produce the following slices, together with their index:
0: slice(0,3)
1: slice(3,5)
2: slice(5,6)
(Both the index and the slice will be used to index/slice into some other arrays.)
I thin... |
I've written a server/client tool which can "check the Six degrees of separation theory" in Russian social network VK.com. Client sends task (which contains two VK IDs) and Server tries to find all connections between these two IDs. I've also written a simple HTTP client just to practice working with sockets.
HTTPClie... |
As mentioned in Project Euler #2 in Swift, I intend to work my way through Project Euler using Swift to make sure there aren't any tricks I'm missing.
This is the problem statement for #3:
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143?
This solution if few... |
I've asked a couple of questions here before regarding my controller, but I think I've finally gotten to understand controllers completely, but I'll never be sure unless I get my code reviewed.
I've moved all my application logic into service classes and placed those inside the application layer of my model layer. I'm ... |
I am making a download manager and in Java. My code is currently working and downloads at 430-450 kb/s. The same file, when downloaded using downthemall, gives 440-460 speed, and when using an Internet download manager, it gives 500+ kb/s.
I am looking for performance pitfalls (inefficient use of CPU, memory and netwo... |
There must be a better way to write this, maybe with a switch statement (which for some reason I can't get to work). Basically, if one of the conditionals is true then the class in the statement is executed. So, in this case, one or any number of combinations could be true.
if (stepOneEdited) {
$(stepOne).addClas... |
I am working on the home page of a website that will have a paginated feed (much like a blog's home page).
One of the requirements is that when a user navigates to a non-existent page, he or she will be redirected to the last available page. For example, when the user navigates to a non-existent page such as page numbe... |
I'd like this code to be improved
Input string: codereview is awesome
Output string: awesome is codereview
My approach:
Reverse the entire string
Reverse each word in a string
package com.arun.reversewords;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Re... |
The following is function that I have written to group a string to groups, based on whether there's consecutive repeated occurrence. Fop example AAAABBBBAAB is grouped as [A+,B+,A+,B]. Is it possible to make below code more pythonic? If yes, how?
def create_groups(alphabets):
""" function group the alphabets to li... |
I wrote a small perl module that dealing with PHP-ish array structures, and I'm going to release it to CPAN.
I want it to be reviewed before the release about the module naming and the code itself.
Could you please give me improvements? Any suggestions are appreciated.
https://github.com/ernix/p5-Object-Squash
use str... |
I have a function, that is used in flask, for logging application errors:
def log_exception(self, exc_info):
self.logger.error('''
Time: %s
Path: %s
HTTP Method: %s
POST_ARGS: %s
GET_ARGS: %s
Client IP Address: %s
User Agent: %s
Us... |
Learn You a Haskell presents an excellent introduction to >>= with an example.
Basically, Pierre is a tight-rope walker that has Birds (Int) on each side of his tight-rope (represented by a tuple (Int, Int)). Birds can land on each side (only one side at a time) with addRight and addLeft. If the difference of birds on ... |
I am porting C# code to F# that makes use of LINQ's Join() extension method. Just as I use that in method call chains, I would of course like to have an F# function to pipe into. However, there is no equivalent in the Seq module, and while the same result could also be achieved with a nested lambda using Seq.where, I'd... |
Problem Statement:
In the 5 by 5 matrix below,
131 673 234 103 18
201 96 342 965 150
630 803 746 422 111
537 699 497 121 956
805 732 524 37 331
the minimal path sum from the top left to
the bottom right, by only moving to the right and down, is
131 → 201 → 96 → 342 → 746 → 422 → 121 → 37 → 331
and is ... |
Problem
The Josephus Problem is a famous mathematical puzzle that goes back to
ancient times. There are many stories to go with the puzzle. One is
that Josephus was one of a group of Jews who were about to be captured
by the Romans. Rather than be enslaved, they chose to commit suicide.
They arranged themselve... |
I've been working on a game so as to fill out something that I can put on a CV and I was writing the main Game class. This shouldn't be a god class, but it should simply be a class that ties together the "wiring" of the game, i.e, it should start listening for input events and should start the game loop and wire any in... |
The problem asks you to take read an integer (number of words to read) and then process words entered counting the number of "HOLES" exist. Letters with HOLES are A B D O P Q and R. Of those B has 2 holes A D O P Q R have 1 and any other letter not listed counts as 0 even lowercase equivalents.
The scope is fairly ... |
I have an a element for a button. The SVG snippet inside links to the containing SVG file at the top of the body.
<a href="#menu" class="head__toggle" title="Toggle Menu">
<svg viewBox="0 0 70.115 53.162" class="head__btn">
<use xlink:href="#skmenu"></use>
</svg>
</a>
When I checked with Codesniffer for W... |
In my Gruntfile, I use the grunt-contrib-watch task to watch a directory for file changes:
watch: {
releases: {
files: ['source/md/releases/*.md'],
tasks: ['process:auto']
}
}
Also, in the Gruntfile, I have a "watch" event handler. Inside this handler, I temporarily store the file path of the f... |
I have created simple class inheritance of an abstract class Pet which is basically the skeleton of all other children classes.
abstract class Pet {
private static $relations = array(
'Cat',
'Dog'
);
public static final function getClassById($id){
return self::$relations[$id];
... |
I would like to find a more efficient way to solve this problem. My current implementation has 3 separate loops through the data.
I'm creating an algorithm to check a collection of prices against an associated collection of minimum prices. Any price that is below the minimum must be adjusted up to meet the minimum. Th... |
Here's my attempt at a Caesar Cipher encoder/decoder.
If given a key, it will encrypt the given string. However, if you do not specify a key, it checks each of the 26 possible keys and returns the one with the highest percentage of words that appear in this file of English words (with a couple additions including 'a' ... |
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
What I've so far learned about Swift is that while the Playground is very cool for tinkering around, it defini... |
I thought I would apply what I learned to make something fun. Its purpose is to type check Pokemon, for anyone familiar with the series. It mostly works but I have two concerns:
Sometimes you write code and you get the pervading feeling you're not using some method, some API or the best approach available; this is one... |
My 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 \$.
Anoth... |
Given an array of ints, is it possible to divide the ints into two
groups, so that the sum of one group is a multiple of 10, and the sum
of the other group is odd. Every int must be in one group or the
other. Write a recursive helper method that takes whatever arguments
you like, and make the initial call to y... |
I have create a UISegmentedControl and a view under it. The view under contains all a view for each segment. I am doing an animation when the segment is changing.
Is a center view that contains all subviews the right approach?
Is the animation is correctly done (this is my first animation in swift) or is there a bett... |
Here is my program that turns numbers into text. It can be extended to millions, billions, trillions and so on. Please review my code and here is what I expect from the users:
Is there any better variable names, function names, you can give me? Or my given names are okay? If you've better variable name ideas, please ... |
I have a navigation bar without a tags:
$('div.nav ul li').on('click', function() {
if($(this).is(':first-child')) {
$("html, body").animate({
scrollTop: "0"
}, 'slow');
} else if($(this).is(':nth-child(2)')) {
$("html, body").animate({
... |
I've implemented a simple C++ STL like list. It's pretty simple, all the constructors and methods haven't been implemented here, but majors are.
#ifndef list_H
#define list_H
#include <iostream>
#include <stdexcept>
template <typename T>
class list {
public:
list <T> & operator = (const list<T> &);
~list();... |
Is this a thread safe collection? Any issues with the code?
public class ThreadSafeKeyedObservableCollection<TKey, TItem> : IObservableList, IList<TItem>
where TItem : IKeyProvider<TKey>
{
#region Fields
private Dictionary<TKey, TItem> _dict;
private IList<TItem> _collection;
private readonly obje... |
I have created Tic Tac Toe in c++ using classes. Is this efficient code?
And GNU GCC compiler gives these warnings:
Warning: control reaches end of non-void function [-Wreturn-type]
Warning: extended initializer lists only available with -std=c++11 or -std=gnu++11 [enabled by default]
warning: non-static data member in... |
I'd like to ask if either my JSON data is ill-conceived and whether how I solved it is particularly inefficient/plain stupid/typical.
Given the following JSON data:
{
"User01": {
"dates & times": {
"date 01": "150",
"date 02": "165",
"date 03": "180"
}
},
... |
I'm looking for general review and improvements on this code that safely gets the next element of a list (and wraps to the first element if you exceed the list). It just seems a little excessive for how simple of a task it is.
It should also be noted that this function will only work for lists that do not contain dupli... |
Can you please tell me if there is a better way to do this?
people = {'123456':{'first': 'Bob', 'last':'Smith'},
'2345343': {'first': 'Jim', 'last': 'Smith'}}
names = list()
first_names= set()
last_names = set()
for device in people:
names.append(device)
first_names.add(people[device]['first'])
l... |
I looked at this question and thought that I could find a much simpler way of doing this, here is the criteria that was given:
My 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 o... |
I've been learning the basics of node over the last couple of days and finally hooked up what I needed. I'm just after someone to comment on if I have gone the right way around this task.
It creates a server which users access to get updates to Orders through server side events.
The events are published through redis ... |
I have figured out how to pass functions around in Lua, and I am using the technique of inserting functions into tables in order to dynamically assign functions to the cards in a trading card game. The functions are assigned when the Card is first created, but more could easily be added later. I am still new to Lua so ... |
I found this one a little bit easier than the previous problems, but I was already familiar with the GCD/LCM formulas.
import Foundation
func printTimeElapsedWhenRunningCode(title:String, operation:()->()) {
let startTime = CFAbsoluteTimeGetCurrent()
operation()
let timeElapsed = CFAbsoluteTimeGetCurrent()... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.