instruction stringlengths 71 71.9k |
|---|
I have the following task:
The Shallow Alto city council has organized a special committee to
review the traffic situation in the city. Despite the fact that there
is nothing whatsoever to do in the city, citizens still write
complaints about the amount of time it takes them to get from one
unexciting location... |
I wrote this script a few days ago to find all files which were taking up over a certain threshold of memory on the hard drive. A hard drive on one of my computers had just 6 GB left, so I needed to clean some space up. I used this to identify bulky folders to find out where the problem was.
Is there anything I could... |
The code should be relatively self-explanatory. I was wondering how much rep the Top Voters on sites did "generate" on a site, in comparison to how much rep they "own".
Therefore I created a little SEDE-Query and I am now wondering, if I follow good SQL-Practices and how the performance of the query could possibly be i... |
This is my first User model I created.
And I wanted to know if there are any good ways I can improve my code? It works with sessions, database and cookies.
I feel like some parts are somewhat written in a weird way, like in my constructor.
I would like to have my code as modular as possible, and maybe if there is anyth... |
This is based on a very similar question I asked, found here.
The intent of this program is to start with a set number of random strings of zeros and ones, and eventually evolve them to find one specific string ('111111').
It fulfils its purpose, but what do you think, and how can I improve it?
import random as r
imp... |
Let's say we've got some SQL queries and want to display the results. Processing takes some time, so I do it multi-threaded.
The following works quite well for me. I reduced the code to the important parts and would be glad to get some comments on it:
Queries and results are stored in thread safe collections.
Concurren... |
If you can't afford the extra level of indirection, that comes with PIMPL, use the implstore! Improvements?
#ifndef IMPLSTORE_HPP
# define IMPLSTORE_HPP
# pragma once
#include <cstddef>
#include <new>
#include <type_traits>
#include <utility>
template <class U, ::std::size_t N = 64>
class implstore
{
public:
imp... |
I have written a piece of MATLAB code that (hopefully) calculates CECT. I have two matrices of psychophysiological measures - one for brain data, one for heart rate; both are of the format epochs * times (i.e., multiple epochs of 10-second long intervals). The supposed outcome is to calculate the correlation between EE... |
I'm new to Haskell, and I'm wondering why my programs are so slow compared to other languages.
Haskell, 6 seconds (x64, -O2):
nextCollatz :: Int -> Int
nextCollatz x = if even x
then quot x 2
else 3 * x + 1
collatzLength :: Int -> Int
collatzLength x = if x == 1
then 0
else 1 + collatzLength (nextColla... |
I'm working on a libcurl binding for NodeJS, and to get info from a curl handler, using curl_easy_getinfo, I've created a template function, the issue, is that the result of the call can be a null pointer.
To make sure this was correctly addressed, I've created a template specialization that handle the edge case:
templ... |
I have created this little dropdown directive in Angular. The idea is that you create a nav element with a ul inside. The directive prepends a chevron and toggles scope.visible when you click it. Two functions watch scope.visible, the first folds the dropdown, and the second reverses the chevron.
I'm attacking this fro... |
I have a solution for pretty printing physical values with the correct suffix (kilo, mega etc.).
I'd like to discuss my solution with you.
# -*- coding: utf-8 -*-
import math
def eng_format(x, unit=''):
e =(math.floor(math.log10(x))//3)*3
sL = ['f', 'p', 'n', 'u', 'm', '', 'k', 'M', 'G']
idx = int(e/3) + ... |
I am trying to write a spellchecker and I wanted to use difflib to implement it. Basically I have a list of technical terms that I added to the standard Unix dictionary (/usr/share/dict/words) that I'm storing in a file I call dictionaryFile.py.
I have another script just called stringSim.py where I import the dictiona... |
I'm writing a financial app that has to get data over a set of dates.
The user specifies the start date, end date, and frequency from a list of choices. (daily, weekly, monthly, quarterly, semi, annually).
There's also a preference option that allows the user to choose whether each period should be the same length ("mo... |
I am trying to make the CommandTimeout value more configurable. I'm wondering if this is best practice to do so?
I add the following to my <appsettings> node in my Web.config file:
<add key="commandTimeValue" value ="60"/>
The I added the following to the top of my controllers under the :
using (var db = new myDAL())... |
I'm using the following function to index ebook data with Lucene. I'm looking to improve the structure and organization of this function.
public string BuildIndex(int pageNum, int pageSize)
{
var watch = new System.Diagnostics.Stopwatch();
watch.Start();
var version = Lucene.Net.Util.Version.LUCENE_30;
... |
I have a table Bill containing Bills with 0...n relationships to Material and Activity (line items on the bill).
My SQL query is essentially bill left join material left join activity.
I have the following insanely tangled code to transform the results into a Map[Bill, (HashSet[Activity], HashSet[Material])].
What's ... |
The Program
I wrote this program as an answer to a question I thought of for Programming Puzzles and Code Golf. To avoid cross-posting, I will only summarize the requirements:
Solve a game in a 3x4 grid that is similar to the fifteen puzzle, except there are colors instead of numbers, and some colors are duplicated; 4... |
The number, 1406357289, is a 0 to 9 pandigital number because it is
made up of each of the digits 0 to 9 in some order, but it also has a
rather interesting sub-string divisibility property.
Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way,
we note the following:
d2d3d4=406 is divisible by 2... |
I'm new to C++ and am doing the C++ 4th Edition Stroustrup book. I expanded on one of the examples, and have a few questions to ask (embedded within the code: ////QUESTION 1-9).
Please provide any critiques, I'd like to bang in safe practice as early as possible. The Vector.h file simply declares these functions, and t... |
#!/usr/bin/env python
import re
import nltk.corpus
def tokenize(text, **kw):
"""
Break down text into a set of unique lower case words.
"""
plain_words = nltk.corpus.abc.words()
stop_words = nltk.corpus.stopwords.words()
# Defaults
kw.setdefault('min_len', 4)
kw.setdefault('max_len', 0... |
I'm writing an IRC bot as a toy project, and one of the goals is to be easy and straight-forward to implement and register new commands.
As I'm new to Go, I don't know which would be the "Go way" for doing it.
This is a working "hello world" command:
package example
import (
"fmt"
"github.com/fabioxgn/go-bot"
... |
I have a DataGridView on the UI (a win form) and objects in the List <Earnings> are shown in the Grid.
View
class Form
{
public BindingSource EarningDetails
{
set {dgEmployeeEarnings.DataSource= value;}
}
}
Presenter Class
class WagePresenter
{
BindingSource BS = new BindingSource();
... |
I have DatabaseContext class.
public interface IDatabaseContext : IDisposable
{
SqlConnection Connection { get; }
}
public class DatabaseContext : IDatabaseContext
{
private readonly string _connectionString;
private SqlConnection _connection;
public DatabaseContext(string connectionString)
{
... |
I need to get a count of correct and incorrect attempts per testID:
select
AttempID,
Test_ID,
Date,
SubjectID,
Date,
sum(Correct) as Correct,
sum(InCorrect) as InCorrect
from tbldemo
group by
AttempID,
Test_ID,
Date,
SubjectID_name,
Date
Do I need to group by each co... |
Learn You a Haskell explains zip4:
--ghci> zip4 [2,3,3] [2,2,2] [5,5,3] [2,2,2]
-- [(2,2,5,2),(3,2,5,2),(3,2,3,2)]
Please critique my implementation:
zip4 :: [a] -> [a] -> [a] -> [a] -> [(a,a,a,a)]
zip4 xs ys zs as = zip4' xs ys zs as
where zip4' [] _ _ _ = []
zip4' ... |
When there is a situation where I want to accumulate a value I see myself using inject/reduce with a conditional statement. E.g., when I want to add 1 to a value each time an element in a list has a certain value I do something like this:
puts names.reduce(0) {|acc, name| triangles.include?(name.points) ? acc+=1 : acc}... |
I am working on an Entity-System-Component engine for games, which basically means an entity is an object that points to components attached to it, and systems retrieve components to modify their data.
I have a class, which is the main data holder, containing the entities, components and system, and methods to dispatch... |
I did some study on the command pattern but most of its examples were in Java so, there must be some difference in implementation in Python. I implemented it in Python with some minor differences, please let me know if something is not correct.
from abc import ABCMeta
from abc import abstractmethod
import inspect
impor... |
I recently wrote a function to calculate the intersection point(s) of two parabolas. Working it out on paper was a nightmare, but I eventually did it (I think it's correct), and ended up with:
\$ x = \frac{\sqrt{c_2 - c_1 + \frac{b_1^2}{4a_1} - \frac{b_2^2}{4a_2} + E}}{\sqrt{a_2 - a_1}} - \frac{b1 - b2}{2(a1 - a2)} \... |
I made a 2048 game clone in Java for training, and I am trying to make it more efficient.
The problem I found is the paintComponent() method always resets all the graphics before doing anything, so I am forced to repaint all 4 rows of the game every time I want to repaint. Obviously I didn't want to override paint() a... |
The javascript I typically need to write seems to be a good fit for the module pattern, e.g., repeatable widgets such as photo galleries, forms, etc. that have their own internal states, but may need to be accessible or editable by other parts of the website.
The particular flavor of the module pattern I've been using ... |
Please note that I'm working on a game on Windows Phone 8 using Monogame. The game is fine (60 FPS) all the time, except when the particle system is activated. This is just a smoke particle system that begins to emit when the player jumps and stop to emit as the player is at "0" y velocity after the jump. When this par... |
Just wanted a few opinions on whether this game's code is efficient, from looking at it, it does look a bit all over the place but I just don't know how to 'tidy' it up to say so. Would love to hear your opinions and even better if you could show me how it's done.
#Here i am importing all necessary modules
import math,... |
I recently solved problems 18/67 in Project Euler. My code is long and I think it could be more effective. I solved the problem with dynamic programming and am new to it, so I want to improve my dynamic programming. I think my running time is acceptable: 0.214 seconds.
import java.io.BufferedReader;
import java.io.Fil... |
I have this algorithm that calculates the matrix determinant using recursive divide-and conquer-approach:
int determ(int a[max][max],int max) {
int det=0, p, h, k, i, j, temp[max][max];
//base case omitted
for(p=0;p<max;p++) {
h = 0;
k = 0;
for(i=1;i<max;i++) {
for( j=0;j<max;j++) {
... |
I am working on a project in which I construct a URL with a valid hostname (but not a blocked hostname) and then execute that URL using RestTemplate from my main thread. I also have a single background thread in my application which parses the data from the URL and extracts the block list of hostnames from it.
If any b... |
Learn You a Haskell presents the Caesar Cipher:
The Caesar cipher is a primitive method of encoding messages by
shifting each character in them by a fixed number of positions in the
alphabet
EDIT
Since I'm not limiting this cipher to letters, it's not actually the Caesarian Cipher.
Thanks to Anonymous. This imple... |
Learn You a Haskell offers the findKey function:
Here's the book's implementation:
findKey :: (Eq k) => k -> [(k,v)] -> v
findKey key xs = snd . head . filter (\(k,v) -> key == k) $ xs
I implemented it with $:
findKey' :: (Eq k) => k -> [(k,v)] -> v
findKey' k xs = snd $ head $ filter ((== k) . fst) xs
As far a... |
I created a Time class. Now I want to modify the code to perform input validation. Hour should be between 0-24, minutes and seconds between 0-59. If class need improvements, please offer suggestions.
Time.h Header File
#ifndef TIME_H
#define TIME_H
class Time
{
private :
int hour;
int minute;
... |
On SO, I asked for a way to do it without variadics. I also provided a typical "normal" implementation with variadics:
template <typename V, typename T>
struct Is_in_tuple;
template <typename V, typename T0, typename... T>
struct Is_in_tuple <V, tuple<T0, T...> >
{
static const bool value = Is_in_tuple<V, tuple<T..... |
I tried use use HTML tags as my own way in PHP using objects.
Is this the correct method of writing or implementing OOP? If not, what is the best way to write such type of code?
<?php
class HTMLCoding {
private $classname;
private $classstyle;
function applyStyle($classname,$classstyle){
$this->cl... |
Given a hashmap (or a "Dictionary") as a JavaScript object, I'd like to get the Key who has the maximum Value - assuming all Values are integers.
In case there's more than one, I don't care which one of them.
Considering
var b = { '1': 9, '2': 7, '3': 7, '4': 9, '5': 3 };
I can extract the desired Key by:
parseInt(_(b... |
I am in process of making debugging output better for client-side application. We have lots of auto-generated Protocol Buffers classes which are used for communication by our protocol.
I am trying to make an function that would enumerate properties in any TObject passed to it, and return JSON-alike string that contains... |
I have a WPF app and a bunch of read/write settings that need to be accessible from various view models. a setting can be any type (string, bool, etc) and all are settable, but only from a 'Settings' view. I also need the view models to be notified when any setting has been updated and which one that was.
Here is an en... |
I have a small "plugin system" (I'm not sure this is the right name). It allow you to store objects (plugins), and then call some methods from each of them. With this approach we have absolutely no overhead on iterating/object pass/callback call.
// Need this SET, because in C++11 auto can only be static const.
// And... |
I'd like to code review generated svg animation, while this might stretch definition of this site, I really hope this is interesting and revelant topic, as this SVG file is really like any other programming language.
I'd like to display certain physical phenomenon, here is example of generated animation (2.5MB of SVG ... |
I have designed a simple state machine for the following diagram:
I am seeking improvements from the community. I especially don't like two things:
When calling performAction I wan't to send only the action without the callback.
And maybe remove the Action enum from the Engine class.
For simplicity everything is add... |
I created this abstract class:
public abstract class MeasurementType {
protected String name;
protected String[] units;
public MeasurementType() {}
public MeasurementType(String name) {
this.name = name;
}
protected void setName(String name) {
this.name = name;
}
protected String getName() {... |
I'm a beginner in JavaScript and lately I've been trying things with RequireJS, I'd like to get some feedback on how good/poor my code is and in what ways it can be improved.
My example below is just loading up social plugins - Facebook Like/Share, Twitter Tweet & Google +1. The code is functional and working.
index.ht... |
Follow up of Pretty print with unit and physical suffix
My first code didn't process negative numbers correctly. Additionally I tried to use all of the helpful input to come up with this solution.
I considered:
precision
testing
spacing tips
P.S.: I use the 'u' instead of U+03BC because I had some difficulties displa... |
I decided to try out Python (3.x) two or so weeks ago, and this is my first real script using it. The program I've written below is slow, clunky, inefficient, inaccurate, and probably poorly coded! But it produces what I want most of the time, and it was really just a project to become accustomed to different Python te... |
I read many times about controller code mustn't be too complicated and so on. I was developing new features in my simple project. I added a function, which allow users to get access to news only in one specified category. Now, if a user writes some of this URL:
/news/common
/news/sport
/news/finance
only news from s... |
Inside my android app, I currently have methods that look like below code. Since they all need a callback object that basically does the same thing and I would like to try to eliminate the duplicated code seen below.
The object that gets posted via the mBus.post(response); statement needs to be the specific type.
@Sub... |
I wrote a zscore algorithm in Ruby that runs fine, but is incredibly slow when I have 8000+ entries to score. Can anyone help me figure out a way to improve my code, please?
module Enumerable
def mean
reduce(:+).to_f / length
end
def sample_variance
sum = inject(0){ |acc, i| acc + (i - mean)**2 }
1... |
As a Lisp (and functional programming) newbie, I wrote the following code that finds the sum of all the multiples of 3 or 5 below 1000, and I suspect that it is lousy:
(defun multiple-of-3-or-5 (x)
(or (eq (mod x 3) 0) (eq (mod x 5) 0)) )
(defun generate-list (min max)
(cond ((> min max) nil)
(t (... |
Is this okay?
public class BaseRepository<T> where T : class
{
private readonly DbContext _dbContext;
public BaseRepository(DbContext dbContext)
{
_dbContext = dbContext;
}
public T Get(Func<T, bool> predicate)
{
return GetAll(predicate).FirstOrDefault();
}
public IEnu... |
I'm a first time user of jQuery (and a huge fan already). I am trying to make the comic picture of an xkcd page onclick to the explanation page.
Here's what I've done.
$("#comic").click(function(){
return window.open("http://www.explainxkcd.com/wiki/index.php/" +
document.URL.split("/")[3]);
});
Is this e... |
I'm fairly new to Python - though not new to programming by any means. I have this Python script and it works perfect for my needs but being new(er) to Python I'm just looking to see if there are any general things I could be doing better or 'more Python-esque'. I recently refactored all of this into what you see now -... |
I'm trying to replace the use of raw pointers with smart pointers in my C++ code. The following bit is from my first attempt at a self-balancing binary tree, though there is nothing self-balancing at the moment. I am worried about some fundamental problems regarding the use of unique pointers.
template <typename K, ty... |
I have a little Mario game I started working on and I realized that its format is very messy. Can anyone critique my code on how to make it better, faster, neater, and easier to access?
frame.java
package EvilMario; //Include this class in the Ev... |
My recent post had some things to fix. I think this should be well structured and written for you.
How does this code look to you? If something needs to be changed please tell me.
// Gets all elements by ID's
function elem(id) {
return document.getElementById(id);
};
//
//Check box id"RadioGroup1_0" will be check... |
I want to erase all memory in a container. Currently I'm using this :
template<typename Cont>
void clear_mem(Cont &container)
{
while (!container.empty())
{
delete container.back();
container.pop_back();
}
}
Should the operation of deleting the memory held by the contents be separated by ... |
I've used the UK Plug -> US Socket and US Plug -> UK Socket analogy. I've also made it possible for UK plug to use a UK socket and a US plug to use a US socket. The output of the SSCCE below is
UKPlug -> UKSocket
USPlug -> USSocket
UKPlug -> UKUSAdapter -> USSocket
USPlug -> USUKAdapter -> UKSocket
And the code
packag... |
This is how I imagine my project's layering:
BLL
Should be independent and contain only pure business logic and properties
Sample Domain Model:
public class Role
{
private UnitOfWork uow { get; set; }
public Role()
{
uow = new UnitOfWork();
}
public int RoleId { get; set; }
public stri... |
I have a requirement where I need to extract pixels of a given rectangle within an image byte[].
More specifically I have an image where I have narrowed an area that I wish to return and keep and the remainder discard. In my case I'm performing face recognition in real time so I don't want to store unnecessary data but... |
I posted not too long ago, asking for tips/improvements I could use on my models. I have changed quite a lot, so I thought I'll give it another go.
My model is supposed to handle all the data I get from the Foursquare API:
venueService.h
typedef void (^TNVenueServiceCompletionBlock)(UIImage *image, NSError *error);
@... |
I see that my code smells. The first file is a controller, and createAction. But I don't know where to delegate this.
BookController.php - Whole controller class
So this is most 'smelly' code to me:
public function createAction(Request $request) {
$user = $this->get('security.context')->getToken()->getUser();
... |
I got this code working but it feels clunky. I am wondering if there is a way I can improve it.
(I'm intermingling JavaScript and jQuery). I'm using jquery-1.11.1.min.js hosted on code.jquery.com.
Here is the jsFiddle
JS:
<script>
$('#indices > div').each(function () {
var url = "http://query.yahooapis.com/v1/public/y... |
Is there a more efficient way of writing this? It seems like so much redundancy that this can be greatly reduced. Basically the only difference is if isNodeWebkit is true then run a function using key code 113 or 112
if (isNodeWebkit) {
$(document).keyup(function (e) {
if (e.which == 113) {
... |
I am trying to copy files from machineB and machineC into machineA as I am running my shell script on machineA.
If the files are not in machineB, then it should be there in machineC for sure. I will try copying the files from machineB first, and if it is not in machineB, then I will try copying the same files from mach... |
I have recently undertaken a project for programming practice based on a simple text editor. Normally this kind of thing wouldn't bother me, but ever since I completed a software architectures module in college, I question everything about how my code is and should be formatted! (probably a good thing?)
I currently onl... |
I'm writing a C# library that's a wrapper around the Yahoo Finance YQL API. I'm stuck on how I want to expose my API to consumers. My design thus far consists of separate interfaces for the different parts of the Yahoo Finance API:
public interface IYahooFinanceCharts {
Task<Image> GetChartAsync(string tickerSymbol... |
This is a Java program that generates a random keyfile (for OTP, for example).
package kfgen;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.security.SecureRandom;
import java.util.Random;
import java.util.Scanner;
public class Kfgen {
// At least it's not ... |
Because std doesn't provide an overloaded version of std::abs for std::size_t, I built a version to calculate distance between unsigned numbers.
It subtracts the smaller one from the larger one, to prevent a negative result, since in unsigned integer it would wrap around.
std::size_t size_type_abs(std::size_t a, std::s... |
In my project, there are some methods which filter some items from a collection. I was told to use the C++ STL whenever I can. But when I use std::copy_if, I feel the code using a simple if-condition looks cleaner.
Which implementation do you like more? Which one is more readable?
std::copy_if version
std::vector<Cat... |
I have recently designed a module which will do bulk upload for different contents. Basically the user will upload an Excel file, I will have to read and validate headers of excel then each value of cell for all columns. I have designed a framework please validate.
Below are the vo.
Template Header details: Excel for e... |
This code reverses each consecutive n elements of a linked list, and for spare nodes, leaves them as they are.
For example, the linked list
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7
for an interval of 3 should result in
3 -> 2 -> 1-> 6 -> 5 -> 4 -> 7
Note that 7 is left as it is as its spare.
I'm looking for code review, opt... |
This is the same problem, but I decided to do it using F#. I'm just interested in how I can improve it.
namespace SalexTaxes
module Product =
type ProductType =
|food = 1
|book = 2
|medical = 3
|other = 4
type Product =
{Name : string;
Type : ProductType; ... |
I am a Java developer who is taking Python for the first time.
I'm sure this is not at all elegant since I am thinking more in C syntax.
"""
This module contains two implementations of the algorithm Sieve of
Eratosthenes.
"""
# import ############################################################### import #
import mat... |
As part of an academic project I wrote a code about dynamic programming that solves the "Three-machine proportionate flow shop problem with unequal machine".
In flow shop scheduling it is usually assumed that the processing
times of the operations belonging to the same job are unrelated. But
when a job corresponds to ... |
The following is an excerpt of a mostly text-based simulator of the iRobot Roomba robot vacuum. I made a class called Roomba that handles everything the roomba does. For those familiar with QT; There is also a class called MainWindow that handles the GUI. This is not that class.
The roomba has several commands that I d... |
As a toy project, I started evaluating the Neo4J graph database and its Rest interface. I'm trying to write a simple graph visualization in JavaScript. In daily business I'm a Java developer and maybe that's the reason why I'm not that happy with my current approach. In Java I would have written a Neo4J class, with inn... |
I am using Boost for reading a config file that is in the .json format. I am using a class to do this and I am calling exit(message) in case of bad values or default value gotten by Boost get() function.
The class is here:
class ConfigFile
{
private:
PTree m_ptConfig;
void failedGetValue(const std::string& messa... |
I am trying to visualize a pointcloud centered around the origin. I also want to have a user controlled rotation for which I found the arcball.
rMat is the model matrix, passed into the shader.
inline QVector3D getArcballVector(const QPoint& pt, int width, int height)
{
QVector3D P = QVector3D(1.0*pt.x ()/width * 2... |
I have posed another question here and I am writing this one for some code review:
class ConfigFile
{
private:
PTree m_ptConfig;
public:
ConfigFile(const std::string& name)
{
json::read_json(name, m_ptConfig);
}
~ConfigFile();
double getVal1()
{
std::string path = "path.to.val1";
double v... |
I have express node.js server code using Passport. It receives a user to authenticate it and send him to some data registration form.
Some concerns:
My whole routes definition depends upon a MongoDB connection using mongo-db ,
but model used by Passport is done through another connection by
mongoose.
The main problem ... |
Let's say I've got this string:
$str = '1-2-3';
and I explode this like so:
$strSplit = explode('-', $str);
what would be the best way to check if I've got the correct number of elements and whether they are numeric (because the input can vary)?
Straightforward, I would say something like this:
if (isset($strSplit[0]... |
I have 3 combo boxes with the same 3 selections in each. If the user picks the same selection a 2nd time, the first combo box resets. I have 3 other sections that will do the same with about 15 combo boxes.
Is there a shorter/compact way to code what I'm doing?
Protected Sub ComBox_GER1_SelectedIndexChanged(sender As O... |
I have a shell script which is being used on an embedded human machine interface (HMI). This script is used to copy a few files from a USB stick to a different place on the device, but with multiple instances of the same file under different names.
If it helps:
OS is Unix-like (BusyBox v1.11.2)
Commands available are ... |
Previous question: BaseRepository for EF6
I've update my code. Is it correct now? I've changed IEnumerable to IQueryable.
public interface IRepository<T> : IDisposable
{
T Get(Expression<Func<T, bool>> predicate);
IQueryable<T> GetWhere(Expression<Func<T, bool>> predicate = null);
void Add(T entity);
... |
I've designed those classes for use in a multiplayer game with possibly very high number of clients for one server. Is this implementation good, or is there something obvious I overlooked or something to improve? I expect this part to have very high performance, so that I can just focus on other things and not come bac... |
I have the situation where as long as the user gives valid input, the StringBuilder object will not be null.
StringBuilder sb = null;
switch(userInput)
{
case 1:
sb = method1();
break;
case 2:
sb = method2();
break;
case 3:
sb = method3();
break;
case 4:
sb = method4();
break;
default:... |
I wrote a program that managed projects and created a set of SQL files for each project. In the logic, I have a few functions that, each time I look at them, I wonder if they could be written in a better way. They are pretty straight forward and compact, however I feel like there are better, more efficient ways of comp... |
My current code:
val headers : Map[String, Seq[String]] = ...
//NOTE: ("key" -> Seq()) is valid entry
headers.toList flatMap {x => x._2 map { y => (x._1 -> y) }}
This feels clumsy...is there a better way to do this?
Goal
I have a Map[String, Seq[String]] representing all the headers in an HTTP request. That needs... |
How can I write my code more efficient (not repeating same code)?
And is there a solution that simplifies the way of having to create a lot of dependency objects over and over again whenever I instantiate a new class (as seen in the load method)?
Any suggestions are welcome.
class Router
{
private $request;
pri... |
I am defining a subclass of a the python dictionary object mpCmd where every item is converted to a lambda. The intended usage is that every item in the dictionary can be called with a single list argument (row) that will return a value based on row. Integers and optionally strings are considered indexes of the row. ... |
I started learning Haskell to see if I can use it at my job. A lot of my work is processing text files for data extraction and analysis.
For my first test, I added a counter at the end of each line from a .csv text file (currently I don't care about the format management).
My current code in Haskell is:
import qualifie... |
I have given an assignment where I have to escape a labyrinth. The goal is to find the shortest way. I have done some research and there seem to be two strategies to solve the problem: the Depth-first search and Breadth-first search, where the first starts at the root (Starting point in maze) and explores as far as pos... |
The problem I have is to find the sum of 2 linked lists. Each linked list node contains 1 digit that represents a number.
My algorithm works but I was wondering if there is a more efficient (speed and memory wise) to solve this problem OR maybe some minor tweaks I can do to reduce space and runtime.
Example: 7 -> 5 -> ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.