instruction stringlengths 71 39k |
|---|
I have a requirement to implement a generic UniqueIdentifier which can cover identifiers like OrderId, TrackingID, scannableId and other Ids. The ids, as they are now, are either Long or String.
Below is my implementation of the UniqueIdentifier class --
public class UniqueIdentifier {
String stringValue;
Long ... |
I am trying to crank up my javascript knowledge by diving into the MVC/MV* design patterns in order to create more reusable and extendable apps.
I am currently sketching out a webapp that involves real time updating of various data feeds.(Facebook and Twitter in the example code)
The app uses jQuery, underscore and na... |
I have a class with a method that will be called multiple times over an object's lifetime to perform some processing steps. This method operates on a mixture of immutable (does not change over the lifetime of the process) data and data that is passed as an argument. The immutable data is comparatively expensive to calc... |
I'm trying to calculate a total value with an array of six numbers and all the basic operators (+-*/).
Suppose you have: 1, 2, 3, 4, 5, 6 and you want to have a total of 10.
Here is my function call a part of my result:
10 = 4 - ((2 - (5 + 6)) + (3 * 1))
10 = (((6 - 4) - 1) - (2 - 3)) * 5
10 = (2 * 3) - ((1 + (5 ... |
I need to pull things from lazy source till timeout is reached in this fashion:
var results = lazySource.SelectMany(item =>
{
//processing goes here
}).Pull(timeout: TimeSpan.FromSeconds(5), times: maxNumberOfIterations);
and I have this solution:
public static class IEnumerableExtensions
{
public static IEnu... |
I'm trying to get in the habit of writing better looking code and more efficient code blocks. I wrote this Twitch TV Application which allows you to add and edit channels and it lets you know when a channel is live. Is there anything I can work on to make my code work / look better?
HTML
<!DOCTYPE html PUBLIC "-//W3C/... |
I am wondering what would be an efficient way to simplify this very simple PHP method and I really lack inspiration:
public function formatToFullDate($countryCode, $hideTime = false)
{
$format = '';
if($hideTime === true)
{
switch($countryCode)
{
case 'us':
case 'ca':... |
I'm using Raphael.js to generate objects which are unique but do basically the same thing. I'm also using Fancybox to display a unique image after a click on a generated object.
Is there a way to write this more concise?
//OBJECT 101
var p1_101 = p1.path("M361,146.773 366.25,192.94 365.917,196.606 366.583,199.69 38... |
I've got this code that I found in a project and I'm wondering how can it be done better:
- (void) setAlpha:(float)alpha {
if (self.superview.tag == noDisableVerticalScrollTag) {
if (alpha == 0 && self.autoresizingMask == UIViewAutoresizingFlexibleLeftMargin) {
if (self.frame.size.width < 10 && ... |
What is the best way to tidy up JavaScript code I have written? It seems very long winded, any suggestions to shorten it?
Note: I'm running it on Wordpress which runs jQuery in nonconflict mode, hence the insane amounts of jQuery.().
jQuery("document").ready(function (jQuery) {
if (jQuery(window).width() < 960) {
... |
I have a fitness function, where inputs x1 to x14 have values between 1:4. Is there a way to make this more efficient? Any suggestions are useful. I need to get the computation time down. A smaller scale pseudocode is below:
%Help improve computation time
function y = Reduce(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x1... |
How could I possibly shorten / clean this up? I suppose mainly clean up the loop at the start asking whether they would like to scramble the code.
def userAnswer(letters):
print("Can you make a word from these letters? "+str(letters)+" :")
x = input("Would you like to scrample the letters? Enter 1 to scramble ... |
I am developing a WEB based GPS system and one of its functionalities is to be able to send messages and routes to GARMIN devices.
I have never been using sockets before, and for some (obvious) reason, I don't feel ready to submit my code before being reviewed by more experienced users.
If some of you have the time to ... |
I'm using PDO, but I want to create my own class for more convenient work with the database.
My main idea in example with comments:
<?php
/**
* User entity. I want to save it into database.
* @Table(name="my_table")
*/
class User {
/**
* Special phpDoc values indicates that this variable should be stored... |
I've been working on a lightweight cookiemanager and version 1 has been completed and works perfectly as intended. I would love to get a review to see where we can improve it.
Where should I throw logical errors? For now I only log.
Its usage is as follows:
Getting cookies can be done by calling Cookiemanger.get(). Yo... |
Basically I have created a function which takes two lists of dicts, for example:
oldList = [{'a':2}, {'v':2}]
newList = [{'a':4},{'c':4},{'e':5}]
My aim is to check for each dictionary key in the oldList and if it has the same dictionary key as in the newList update the dictionary, else append to the oldList.
So in t... |
Here is a problem I am trying to solve: trying to find missing photographs from a sequence of filenames. The problem boils down to: given an unsorted list of integers, return a sorted list of missing numbers. Below is my code.
What I am looking for are:
Are there more efficient algorithms?
Is there any performance pro... |
Number can be very big.Script is taking number as a "number" list and crossing from 10-decimal based system to n-based system until list equals "5".I don't use letters like in 16-base system(hex).Example if result will be AB5 in hex list will be [10,11,5]. Some ideas how to optimize or/and change this to recursion?Any ... |
In such an array:
$arr = Array (
[key0] => Array (
[subkey0] => Array (
[0] => "value0"
[1] => "value1"
)
[subkey1] => Array (
[0] => "value0"
[1] => "value1"
)
)
[key1] => Array (
[subkey0] => Array (
[0] =>... |
I have an http library in Ruby with a Response class, I have broken it down into smaller methods to avoid having a big intialize method, but then I end up with this:
def initialize(res)
@res = res
@headers = Hash.new
if res.empty?
raise InvalidHttpResponse
end
split_data
parse_headers
... |
I was using foo(bar) as it's adopted for functional programming.
console.log(
join(
map(function(row){ return row.join(" "); },
tablify(
map(function(text){return align(text},
view),
20))),
"\n");
Now, with dot operator:
view.map(function(... |
I am using PHP to build a REST API. I want to receive requests from the URL in the following format:
http://mydomain.com/api/format/method?app_id=value&call=encrypted_request
So, I have modified my .htaccess as:
Options +FollowSymLinks
IndexIgnore */*
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond... |
I've recently picked up PHP, for the first assignment in my IT-security class I decided to code it in PHP.
The algorithm is an alternation of the Caesar cipher, instead of using a fixed number to push the letters a keyword is applied to rearrange a couple of letters and then move the rest of the letters accordingly.
I... |
Basically I have a 2d list containing movies. Movies are specified by name, version and description. For example
['Jaws', 1, 'Movie about sharks'] - where Jaws = name, 1 = version and Movie about sharks = description.
My result is a dictionary which contains a map between name and description. But name should be updat... |
There have been many posts here about enums in python, but none seem to be both type safe and simple. Here is my attempt at it. Please let me know if you see anything obviously wrong with it.
def typeSafeEnum(enumName, *sequential):
topLevel = type(enumName, (object,), dict(zip(sequential, [None] * len(sequential)... |
Is there any way I can simplify this inefficient piece of JavaScript?
$(function () {
var $carousel = $('#carousel');
var $switch = $('#switch');
var $header = $('#header');
var $submit = $('#submit');
$carousel.bind('slid', function() {
var index = $('#carousel .item').index($('#carousel .... |
I'm working on an ASP.NET project using VB.NET that uses Dapper and the code as implemented so far runs fine with just me testing. In the example below, Dapper calls a stored proc.
But I am wondering primarily right now if the method of generating an open connection (see dbConnFactory below) implemented in the Domain ... |
I have a function that I need to optimize:
def search(graph, node, maxdepth = 10, depth = 0):
nodes = []
for neighbor in graph.neighbors_iter(node):
if graph.node[neighbor].get('station', False):
return neighbor
nodes.append(neighbor)
for i in nodes:
if depth+1 > maxdepth... |
I've implemented selection sort, heap sort, insertion sort, and iterative quicksort using C++11. Am I using the correct STL data structures/algorithms? Am I using move semantics correctly in my code?
#include <algorithm>
#include <vector>
#include <queue>
#include <functional>
#include <iterator>
#include <utility>
#in... |
I am learning ORM using Hibernate by creating a movie rental application. Currently, I have the following three entities for persistence:
User
Movie
Rental (composite element for many-to-many mapping between above two)
Now, to handle the cart updates, I have the following code in a session scoped bean:
@ManagedBean
@... |
The scripts below, I've obtained through tutorials and edited the best I know how. It all works - but I'd like to place them in one, external script. If at all possible, I'd appreciate some help in cleaning up the code too. I've a feeling some of it is redundant.
With the client-side validation script, I have "Name," "... |
Looking at knockout for the first time, would like to know if I'm approaching it correctly.
Here's a live example:
http://jsfiddle.net/fergal_doyle/xhAe8/1/
I have a "car" select, and an "other" input to allow values not present in the select box. When "other" is populated, it over-rides "car" by disabling it and a com... |
I'm creating a MUD and am running into some design issues regarding Items.
Items are stored in an ItemDatabase after being read from a JSON file.
template <typename ItemType>
static void load(std::string const& filename)
{
PropertyTree propertyTree;
boost::property_tree::read_json(filename, propertyTree);
... |
This is my first real program, though it has gone through a few major revisions. Anyhow, I am sure that there is a lot I could have done better, cleaner or safer.
Can anyone see anything I really need to work on or fix?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <getopt.h>
#in... |
I have a weighted BFS search in python for networkx that I want to optimize:
def bfs(graph, node, attribute, max = 10000):
# cProfile shows this taking up the most time. Maybe I could use heapq directly? Or maybe I would get more of a benefit making it multithreaded?
queue = Queue.PriorityQueue()
num = 0
... |
I want to use some constant in both server side and client side.
Currently, I use PHP reflection in order to synchronize PHP constants and Javascript constants. But for the maintainable reason, it's not a best practise.
For example:
interface IType{
//...
const ID_TYPE_TEXT = 1000;
const ID_TYPE_NUMBER = 2000;
... |
I'm implementing an is_dir() function to determine if a given item is a directory or a file for FTP/FTPS connections. Currently, I have two methods: one using PHP's FTP wrapper for the is_dir() function and another recommended in the help page for the ftp_chdir() function.
Here's the first one (protocol wrapper):
if ($... |
In Rails 3, I have two models: Nutrient and Recommendation:
Nutrient has_many Recommendation
Recommendation belongs_to Nutrient
I am trying to implement the create method of the recommendation in the controller. Is this the proper way to do it?
def create
nutrient_id = params[:recommendation][:nutrient_id]
if nut... |
I have a number of functions inside class, which serve my scripts to provide functionality such as a login, which is the function I am going to be using as my examples.
public static function GetCredentials ($Argument_1, $Argument_2){
$GetUserInformation = self::$Database->prepare("SELECT Username,Passwor... |
I have to write methods for a binary tree that has positive integers as values. These are not full methods. They are supposed to be written in pseudocode.
a) Count number of nodes in a Tree
countNodes(TreeNode root){
if(root == null)
return 0;
else{
TreeNode left = root.getLeftChild();
T... |
private eFileStatus CheckConfigSettings()
{
mFileStatus = mXMLHelper.CheckElement(eElementName.StartLanguage.ToString(), out mContent);
if (eFileStatus.OK != mFileStatus)
{
return mFileStatus;
}
else if (eFileStatus.OK == mFileStatus && mConten... |
I know that Swing isn't true MVC:
Using this modified MVC helps to more completely decouple the model
from the view.
Leaving aside the veracity of the above claim, the problem I run into is that I can't seem to just drop a Page into a JList, but have to first extract a List (data) from the Page object. This just s... |
My implemented regex pattern contains two repeating symbols: \d{2}\. and <p>(.*)</p>. I want to get rid of this repetition and asked myself if there is a way to loop in Python's regular expression implementation.
Note: I do not ask for help to parse a XML file. There are many great tutorials, howtos and libraries. I am... |
Teachers can raise 'dramas' which are when students forget equipment, don't do homework or are flagged for concern. Each drama for each student is stored as a separate record.
I seek a list of all unresolved dramas, grouped by student & date. So if on one day a student forgets their homework and doesn't have equipment,... |
This started simple, as most things do. I just wanted a little structure to hold polar coordinates for a totally minor class. But starting with this answer and borrowing from existing Objective-C concepts like CGPoint and CGSize, the simple struct quickly morphed into a more complete solution.
I have this all in a _pol... |
In the snippet below the three exceptions I declare in the throws clause are all thrown by BeanUtils.setProperty(), which is a third party library.
Is letting these three exceptions "bubble upwards" with a throws declaration bad style? Is it better to wrap them in my own RoleBeanException and throw that?
public BeanRo... |
As an interesting exercise in Python 3.3, I implemented a Trie (also known as a Prefix Tree).
Example usages
Create from list of key-value-tuples
mapping = (('she', 1), ('sells', 5), ('sea', 10), ('shells', 19), ('today', 5))
trie = Trie.from_mapping(mapping)
some_prefix = 'sh'
some_key = 'today'
print('Keys:', *trie)... |
Here is my first try at Google's Go language, trying to solve Project Euler Problem 10:
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
Any suggestions on the style and usage (best practice) of Go?
package main
import "fmt"
var primes = []uint64{2, 3}
func Ch... |
I'm working on a simple superfeedr powered rails app here.
Based on the superfeedr-rack gem documentation, I'm doing this to initialize the middleware (snippet from application.rb config block):
Configuration = YAML.load_file(Rails.root.join('config', 'config.yml'))
config.middleware.use Rack::Superfeedr, { :host => C... |
I have the below program
class Program
{
static void Main(string[] args)
{
List<Assembly> failedAssemblies = LoadAssembly();
string batchFile = "D:\\1" + ".bat";
FileStream fs = File.Create(batchFile);
fs.Close();
using (StreamWriter outF... |
I get great FPS with this as is, but I'm a performance freak and I don't know AffineTransform or the Java graphics libraries very well. I'm sure there is something I could be doing differently to make this faster, but I can't think of anything, other than it looks like the scale transformation gives me a big performanc... |
Link to a full functional solution.
I'm working on a physics based algorithm, and I find myself working a lot with functions of style
double GetSpeed(double acceleration, double angle, double resistance)
A lot of physical values are passed from function to function as double, and it is a nightmare. I fail a lot at gi... |
It doesn't happen often, but I sometimes come across cases where I miss Java's checked exceptions, especially in medium sized methods of about 30 odd lines that call outward. Often, the following pattern emerges:
bool Foo(){
LibType l1 = new LibType("bla");
LibType2 smt = l1.bar("context");
...
...
}
and I wan... |
The code below is for testing Primes.
testPrime(100000);
testPrime(1000000);
testPrime(10000000);
testPrime(100000000);
Now my goal is to make the code super fast at finding prime number, min-max, close prime.
Are there any improvements that can be done to the code below to improve the speed for IsPrime?
import java.u... |
I want to create a file consisting take rows of distinct numbers in ascending order. They are randomly taken from the first total integer. The file will be used to make an excerpt as discussed here.
I realize that my naming convention for identifiers below is not good but please ignore it for the sake of simplicity.
us... |
I have to write a program that changes a string's vowels, consonants and other symbols into C, V respectively 0. I've done this but I wonder if there is a more efficient and elegant way to do it. Would appreciate input.
(defun string-to-list (string)
(loop for char across string collect char))
(defun is-vowel (char) (... |
I have a dashboard like interface, that can have many tabs. There can be as many or as few tabs as the user likes, with the user being allowed to re order them as they wish. Exactly like browsers do.
My problem is moving the tabs position, for example, look at these tabs:
[Sales] [Admin] [Finance] [Development]
If th... |
I wrote a simple program to remove duplicates from a String without using additional buffer.
The program should filter the duplicates and return just the unique string.
Example:
Input:
FOOOOOOOOLLLLLOWWWWWWWWWW UUUUP
Output:
FOLW UP
I just want to know if the below solution is a good solution for my problem state... |
I've constructed a simple class whose entire purpose is to hash passwords securely and simply.
The catch is the PHP version is probably going to be 5.2.x. This means:
No CRYPT_BLOWFISH
Obviously no password_hash().
The question is, is the following secure? Can it be improved?
/**
* Class Hasher
*
* @package Depend... |
I have made a class to import into my projects to more easily handle the state of the keyboard so I can use stuff like:
if(Keys.returnKey(37)){
As opposed to setting up key listeners.
Please give this code a general review:
/*
ALWAYS DO THIS FIRST:
Keys.init(stage);
THEN YOU CAN DO THESE:
Keys.returnK... |
I'm implementing a login system on app engine (I have to, so please don't tell me to use the User service, or an other way to delegate authentication), and I'm wondering whether this setup is secure.
from pbkdf2 import PBKDF2
import os
salt = os.urandom(8)
password = PBKDF2(passphrase, salt).read(32).encode("hex")... |
I've never done Java GUI's before. After much trouble I've gotten my GUI to look how I want, however it feels as if my code is very inefficient, as if I'm going about this the wrong way?
//main panels
private JPanel westPanel = new JPanel(new BorderLayout());
private JPanel eastPanel = new JPanel(new BorderLayout(... |
I am new to C++ and am looking to expand my knowledge. Below is a simple program that I've made. I would like to know how it could be improved, in any way. The introduction of new ways to do things is what I am looking for. These could be anything from improving efficiency to validating input - just whatever you think ... |
I am bashing my head against how to solve this puzzle. Is there any super SQL expert out there who can lend some help
I have a database with the following structure.
adjlevel | scheme | holder | client | companyID | Rate
A rate can be held in this table based on either of the following keys
level + companyId + scheme... |
Which is best practice for creating an enum-like lookup for templates? I enjoy being able to bring up my templates with VS IntelliSense so either works for me.
Option 1 (enum/Dictionary combo):
public enum Template
{
AccountInformation = 1,
Registration = 2,
Signed = 3
}
static readonly IDictionary<Template... |
I have written a program that, given an amount, returns the interest you would receive on that figure. There are 3 interest rate bands as follows:
1% - £0 to £1000
2% - £1000 to £5000
3% - £5000+
Can anyone tell me if the following is a good solution or are the if statements too restrictive?
public BigDecimal calc(Bi... |
I'm working on a project where I need to solve for one of the roots of a quartic polymonial many, many times. Is there a better, i.e., faster way to do this? Should I write my own C-library? The example code is below.
# this code calculates the pH of a solution as it is
# titrated with base and then plots it.
impor... |
I have created the following stored procedure which duplicates a record in a table and also all its related records in other tables however since I am a newbie to SQL I would appreciate it if someone could review my code and show me how it could be improved and whether there are any hazards.
USE [Neptune2Dev]
GO... |
This code seems to work, but I'd like someone with shell-fu to review it.
Is the temp file a good idea? How would I do without?
Is sed the right tool?
Any other general advice for improving my shell script
Script/Code to Review:
# Grab max field lengths from each .hbm.xml file and
# put them into the corresponding .... |
Please check if my tables specs agree with business rules. Also, please explain the differences between CONSTRAINT, FOREIGN KEY and CONSTRAINT FOREIGN KEY.
I have four MySQL tables (USER, NAME, PATIENT and DOCTOR) with the following rules:
A patient must have a name
A patient can be a user
A doctor must have a name
A ... |
I'm self-studying Java and have a question about one of the end-of-chapter exercises. The chapter focus is on inheritance and the book hasn't officially introduced polymorphism so I'm trying to stay within those bounds.
The exercise is:
Write an inheritance hierarchy for classes Quadrilateral, Trapezoid, Parallelog... |
I have completed my homework with directions as follows:
Declare and implement a class named Binary. This class will have a
method named printB(int n) that prints all binary strings of length n.
For n = 3, it will print
000
001
010
011
100
101
110
111
in this order.
Is there any way to make this shorter or more ... |
The code below implements an intrusive lock-free queue that supports multiple concurrent producers and consumers.
Some features:
Producers and consumers work on separate ends of the queue most of the time.
The fast path for producers and consumers has 4 atomic ops.
Version numbers are used to prevent the ABA problem.
... |
I've created the following string manipulation function for randomizing my passed string in Lua:
require "string"
require "math"
math.randomseed( os.time() )
function string.random( self )
local tTemporary, tNew = {}, {}
if not self or self:len() < 5 then
return nil
end
self:gsub( "%a", functi... |
I've implemented a simple program that finds all prime numbers between two integer inputs using Sieve of Eratosthenes, but the online judge is still complaining that the time limit is exceeding. Maybe I'm doing something wrong, but how can I optimize (or debug if necessary) my code?
#include <iostream>
#include <cmath>... |
Think of the numpad number layout.
hvd = horizontal, vertical or diagonal
coord = 1,2 or 3 if horizontal or vertical and 1 or 2 if diagonal (1 is up, 2 is down)...
hello('v', 2) - Asking for the second vertical column etc
def hello(hvd, coord):
if hvd == 'h':
print "horizontal it is"
if coord == 1:
... |
Is this the most efficient way to find if a number is prime? I can't think of a better way and it seems to run pretty quickly.
public boolean primes(int num){
for(int i = 2; i < num; i++){
if(num % i == 0){
System.out.println(num + " is not prime");
return false;
}
}
... |
Is there anything wrong with doing this:
Public Class Form1
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
For value As Integer = 0 To 1000000
Dim p As New Person
p.ID = value
p.DoSomething()
p = Nothing
Nex... |
I've leaped into SASS and am loving it. I'm asking for comments here on whether my SASS is well-formatted.
Here's the original CSS based on Zurb's Foundation Pagination styles, but adapted for use with Laravel's built-in pagination:
div.pagination ul { display: block; height: 24px; margin-left: -5px; }
div.pagination... |
I have written a small snippet to validate a substring in a string in O(n). I have tested the code using some combinations. I require your help to let me know if there are any bugs in my code with respect to any other cases that I might have missed out:-
class StringClass( object ):
def __init__( self, s ):
... |
I'm working on Project Euler's problem #23, which is
Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers
I came up with this algorithm. Find all abundant numbers under 28123 (defined Numeric#abundant?), this is slow and could be faster if skipped primes, but is fairly ... |
This plugin is meant to filter through a table based on column header text that matches options given to it.
check it out here: Filter Table Plugin
Plugin code below for reference:
//framework from http://jqueryboilerplate.com/
; (function ($, window, document, undefined) {
var pluginName = "filterTable",
... |
I have a class that I inherited from someone else. It is doing a P/Invoke on CopyFileEx to copy a file (we are using UNC shares if that matters). The code is marked unsafe but I thought you only needed to use that when dealing with raw pointers, if you are using IntPtr only your code does not need to be marked unsafe.
... |
In my Blackjack game so far, I have multiple classes that access each other frequently. For example, this is my hit() function for the Game class:
void Game::hit(unsigned playerNum)
{
Card newCard = deck.deal();
players[playerNum].getPlayerHand()[0].getHandCards().push_back(newCard);
}
First, a new Card objec... |
I run into this often. I have two functions very similar, that if I combine would be more DRY but if I didn't would be easier to read and make more sense.
In this case I have two implementations of fade, one using setInterval and one using setTimeout.
How do I not get stuck deciding between Dry vs. readability. I hop... |
This is a follow-up to this question my code has evolved since so I'm reposting my question.
What is the best way to tidy this up? How can this be refined? I am finding it's thrashing the layout quite a lot and the scroll function seems to lag.
;(function ($, window) {
var main = $("#swab"),
sbContainer = $("#sb-co... |
I wrote an HTTP server for the management of scores for users and levels.
It can return the highest score per level. It has a simple login with session-key.
What do you think could be improved in this code? What's wrong? And particularly, are there any multi-threading issues that I didn't take into account?
//********... |
I've implemented a very simple in-memory "database" just as an exercise. I wanted to see if there's anything obvious I should be doing that fits more of the Haskell way of doing things.
import qualified Data.Map as M
type History = [String]
data Result = Result (Maybe String) Bool DB
data Command = Command { name :... |
I am trying to simply present a table in HTML that is stored in a MySQL database. I would like to use Object Oriented PHP to access and fetch the data for the table. I have spent some time learning the different elements and have tried to put together a generic template I can use to access the tables in the database.
Q... |
Only these formats are accepted.
1.1.1
1.1.1-r
1.1.1-b
1.1.1-r1
1.1.1-b1
I wrote this code. What don't I like in it? I used parentheses and now I have two groups. In fact, I don't need to do anything with groups. And there might be some bugs as well.
package com.sandbox;
import java.util.regex.Matcher;
import java.u... |
Each class of my project has several inputs and outputs. Each input, the same as output, depends on it's own set of value-datatype.
I need to provide a mechanism to forward data streams from one instance to another, with ability to split that streams and to combine several streams into one.
There are a lot of such clas... |
How would you write this?
string halfADayOff = "Half a day off";
string oneDayOff = "One day off";
string days = "NoDaysOff";
if (typeOfDelegation)
{
if ((differenceInDays == 0) && (arrivalDay.TimeOfDay.Hours > 22))
days = halfADayOff;
else if ((differenceInDays == 1) && (arrivalDay.Ti... |
I develop my first async TCP socket server and client program in c# and would like to review the first parts of it. I like to get some information’s about smelly code that I missed and what I could improve in the program. I know it's a little bit much code, but it would awesome if you help me to improve my skills!
I ha... |
I am writing a CSV file generator that's filtering through about seven million database entries (MySQL backend). This part is especially slow and I was wondering if there is a way to make it much faster. I was thinking of wiring to a temp file first before serving it and then deleting the file.
The Station.header() re... |
I've been playing around with 8051 assembly lately and thought I would make a little project of implementing RC4, since it is pretty interesting and the algorithm doesn't seem too hard. Plus, taking mod 256 is REALLY easy when you're only working with single bytes.
Below I've included my (hopefully well-commented) code... |
I am writing Python code for a Tic Tac Toe game. I need to write a function that takes in three inputs: board, x, and y. Board being the current display of the board and then x and y being values of 0, 1, or 2. The game is set up to ask the user for coordinates.
def CheckVictory(board, x, y):
#check if previous... |
I'm trying to get the most out of this code, so I would understand what should I look for in the future. The code below, works fine, I just want to make it more efficient.
Any suggestions?
from mrjob.job import MRJob
import operator
import re
# append result from each reducer
output_words = []
class MRSudo(MRJob):
... |
Looking for a review of my first published jQuery Plugin. It's for TreeViews, very basic example demo can be seen at: Demo
Everything works fine, just looking to see if I can get some feedback on things that I may be doing wrong best practices wise and/or things I could be doing better.
(function ( $ ) {
var methods... |
public static void listPrimesThree(int maxNum){
long startTime = System.currentTimeMillis();
boolean[] booleanArray = new boolean[maxNum+1];
int root = (int)Math.sqrt(maxNum);
for (int m = 2; m <= root; m++){
for (int k = m*m; k <= maxNum; k+=m){
booleanArray[k] = true;
}
}
for (int m = 3; m <= maxNum; m+=2){... |
There may not be a "right" way to do it, but I'm inexperienced in functional programming. I'd like some feedback on how the code can be written in a more idiomatic way.
Here it is:
import Data.Maybe (fromJust, isJust)
sepInt n = if n >= 10
then ( sepInt ( n `div` 10 ) ) ++ ((n `mod` 10):[])
el... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.