instruction stringlengths 71 71.9k |
|---|
Here I have class that supposed to take dictionaries of product objects and their articles (kind of unique identifier) from queue and insert or update them in database table.
Received dictionary looks like this:
products_and_articles= {'products':[],'articles':[]}
Please suggest any improvements I can make to this cla... |
The counting sort for integers counts the amount of each integer, then traverses the count entries in order, and for each entry inserts the integer representing the bucket into the array as many times as its entry denotes.
This is basically same idea, but for general objects. The algorithm makes a pass through the enti... |
I'm working on a personal project to practice my programming skills and I came to this problem. I tried to create a program that will find the missing number in a array.
I'm looking forward to upgrading this program and am trying to find the missing numbers in a array. Yes, with an 's'.
/*******************************... |
I have written the code as best that I know how but I am unsure that the questions asked are being fulfilled. Any advice to improve this code would really help me.
Question asked:
Create a new project in NetBeans called Payrollimplement
Create a new class in the same project called PayrollCal
In this class you will ... |
Can this be shortened to one line?
bool areVersionsEqual = documentComparer.Equals(version, imported);
if (areVersionsEqual == false)
{
changedDocument.Add(imported);
}
|
I wish to redirect users to the login page if they attempt to visit a page which requires them to be logged in. After logging in, however, I want to redirect the user back to their original destination. I've written a "redirect.php" script which is to be included on all such pages:
<?php
require "session.php";
if(!$use... |
We have the following code which takes about 5 seconds in a modern computer, however the application is also executed on old PCs with Windows XP, and in there it takes 5 minutes to load. I know the old pcs are slow, but 5 minutes its just ridiculous slow, this code was developed by someone else and now we have to imp... |
I just tried PHP Traits for the first time, to keep my code DRY :
<?php
namespace Acme\DemoBundle\Model;
trait CheckPermissionTrait
{
protected function checkPermission($object_id)
{
$judge = $this->container->get('acme_judge');
$user = $this->container->get('security.context')->getToken()->g... |
I am implementing a framework for validating orders. User creates a number of orders (Amazon orders for example), before he submits the orders and pays for shipment, whenever he revises anything, I need to run a couple of checkers against the orders and show corresponding warnings and errors produced by the checkers.
T... |
I have a domain object that I have no control over which itself contains a collection of this same type. This is a classical hierarichal representation like in a tree node hierarchy. I would like to be able to enumerate the whole hierarchy in a single call so I came up with this extension method:
public static class My... |
Sometimes I need to search for dependencies in the classpath entries in the manifest of jar files. A jar manifest with classpaths looks like this:
Manifest-Version: 1.0
Created-By: 1.6.0_29 (Sun Microsystems Inc.)
Class-Path: spring-aop-3.2.0.jar spring-aspects-3.2.0.jar spring-beans
-3.2.0.jar spring-context-3.2.0.j... |
I am trying to exploit asynchronism for parallelism. This is my first attempt at a parallel event subscriber. In your expert opinions, is this a valid approach?
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using EventStore.ClientAPI;
namespace Sandbox
{
public class SomeEventSubscr... |
I thought that developing an app in Python should be easier than learning Java. I finally got my isprime app to work but it looks ugly. When I write GUI code I always find myself typing in very long code. This is not Code Golf for sure, but 70 lines for such a simple app is too much in opinion. The shorter (reasonably)... |
I've been happily using jQuery, creating vars and binding events in my modules (which have only a little bit of JS). But recently I needed to add an anonymous functions to my code and after investigating some more, I learned about modular patterns and encapsulation.
So what I'm trying to teach myself is to write clean,... |
private void SendActivationEmail(MembershipUser user)
{
var message = new MailMessage();
message.To.Add(user.Email);
message.Subject = "Attorney Event Notification Activation";
string urlBase = Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath;
string ActivationUrl = "/Activat... |
I'm really inexperienced with cycles, so I want to make this code shorter. As far as I know, I've made a recursive cycle.
for (Pointers[0] = 0; Pointers[0] < 8; Pointers[0]++)
if (AdjM[Pointers[0], VertStart + 0])
{
for (Pointers[1] = 0; Pointers[1] < 8; Pointers[1]++)
{
if (AdjM[Poi... |
I have a method within a class that validates all proxy addresses are valid on initialization. I've tried to refactor this a bit, but this seems to be the best I can do. Any suggestions and/or tips as to how I can possibly improve this method?
def valid?(proxies)
return false if !proxies.is_a?(Array) || proxies.empty... |
Previous question:
Rotate image 90 degree clockwise
In this code I have used tail recursive, which is bad. Time complexity is still \$O(N^2)\$, which is worse-case. The only good part is memory complexity.
How can I improve the recursive part of this code?
#include <iostream>
#include <iomanip>
#include <algorithm>
#in... |
I'm trying to learn how to use makefiles, and this is my attempt at making a makefile that compiles source files in a source directory (src/) into object files that are created in a bin directory.
##########################################
# Editable options #
#####################################... |
I have a POJO as shown below which will have hostname and other attributes.
public class MachineInfo {
private String hostname;
// getters and setters here
}
I have my below method from which I need to randomly pick a hostname which is up for more than 10 minutes from machines list. The checkHostUptime meth... |
I was recently given this programming challenge on an interview, and I decided to use javascript to solve it. I did, but I'm not happy with my implementation. I can't help thinking there must be a better way of doing this.
The exercise goes like this:
Given an array of integers, write a function that returns an arra... |
I got thousands of files with a specific file extension in thousands of sub folders. Now, what is the fastest way to search with a pattern? I tried the method DirectoryInfo.GetFiles(rootfolder) (~8 minutes) and a recursive custom method (~5 minutes).
private void WalkDirectoryTree(DirectoryInfo dr, string searchname)
... |
I was eager to learn the implementation details behind windowing GUI systems. Because I am mostly a high level programmer having not much experience in low-level stuff, I had to simulate it instead of implementing the actual one such as Windows Explorer, KDE, Gnome, X11 and Mac OSX Aqua.
There is the list of things you... |
This might be difficult for me to describe clearly but I will try anyway. Also note that this is entirely speculative; it might not even be able to run any faster (that is why I am asking).
This is a question directed at performance. I have been trying to improve the performance of a method and have managed to improve... |
I based this implementation on CountedPtr in The C++ Standard Library book by Nicolai Josuttis (page 222) and also available online here.
I know that I can use the C++11 smart pointers but this is a learning exercise and also for some projects an earlier compiler must be used.
I didn't understand the need for the actua... |
I created the following app (only saves the notes in an array so no a proper note taking app). I would like to know how I would make this code more object orientated.
JSFiddle
script.js:
$(document).ready(function() {
var notesArray = [],
count = 0;
function listRefresh() {
$('#list').empty();... |
I have a task to construct a long properly formatted string in Java. This string will be then used as a header of the logfile that we write during the program execution. As the program runs on server continuously, this string may need to be returned via the overridden method more than once. I have used multiple StringB... |
I am new to node.js and I am just wondering what you think about this code. For me, it seems there are too many conditions in the code. Is there any way to refactor it?
var removeQuestions = function(questions) {
if (questions.length < 1)
return;
var group_name = questions[0].group;
var metagroup_n... |
I'd like advice on how this could be written more efficiently, idiomatically, or just anything that could be improved upon.
I'd also like to know if there's an alternative to my forString method; I couldn't find anything similar in the library (and Scalex seems to be down, so I couldn't search).
There are 2 provided wa... |
I have an application using c# and MVC5, with RazorEngine.
My application manages requests (orders from clients) and I need to show them in tables. To achieve this I have a Controller (HistoryController), a View (Index) and a Model (MaterialRequestModel) which takes several parameters in the constructor:
public Mater... |
Given an instance of SQL Server, imagine there's a table named Configuration, which has three columns: ID, Name, and Data. There should be no duplicate rows for Name.
Now imagine that you want to select the data stored for a particular configuration, but if that configuration doesn't have a row in the table, then you ... |
This is a pointer class of mine that I would like to have reviewed. Right now it only allocates in the stack and has no copy or move operations.
template<typename T>
class Ptr {
public:
Ptr(T* t, int s = 1) :p{t},sz{s} { }
T& operator*() {
check_range();
return *p;
}
T& operator[](int i)... |
below is a working example of code in which you can create car colors and cars using these colors with XML POST messages. And request all cars and colors formatted in XML using a GET message. I am running this on WildFly 8.2. The code is working as expected, I would like to know if there are any enhancements possible. ... |
Some fellow code reviewers (hi @Janos!) have been inquiring about a SEDE query to allow to check progress of the Red Shirt "hat" progression.
Try it here!
Background
Red Shirt
cast 5 downvotes on posts that are later deleted or closed
Limitations
There are certain Stack Exchange limitations which make querying th... |
I am trying to learn how to write proper code in python, and stumbled upon the following problem.
Bob is given a set of building blocks b, and a number n of towers
to build. Since we are in communist land the towers should have as
equal of an height as possible. The catch is that you are only given
a maximum of ... |
I would like to use erlang to create an online, web-based game. I thought it would make sense to start with something easy, so I chose tic-tac-toe (which seems like a popular choice here). I am implementing users, players and the rules engine as finite state machines using the OTP gen_fsm.
The first step I decided to t... |
This will compile, but I'm thinking that this implementation of read/write is very hard coded and would not be easily adapted to larger situations where large XML documents are being processed or if they are in a different format structure.
using System;
using System.Collections.Generic;
using System.Linq;
using Syste... |
I've been prototyping a Match 3 game (Bejeweled clone) because I have an interesting concept for one, and because it is good practice. One key aspect of my version is that the matches must contain one of the swapped orbs. Therefore matches elsewhere on the board do not get destroyed (and for now there are no combos).... |
I threw together this Python function to check if a User has a certain Permission.
First of all, Permissions have this kind of format: category1.category2.some.task
and can also include wildcards like this: app.view.*
All the permissions a User has are stored in a list, so for example:
["app.cat1.*", "app.cat2.do.somet... |
I've been working on this site.
The designers original inspiration for the column layout came from this site. I've been trying to get the animation as smooth as possible, to match the smoothness of the site referenced; but it's still choppy.
(function ($ , window, document ) {
var c,page,href,pagewidth,
pr... |
I have written this code representing a class hierarchy of character classes, and a world class to print their properties.
Is anything unclear about this code? Am I utilizing good practices?
class Human{
protected String name;
protected int health;
protected int armorLevel;
protected int magicLevel... |
The biggest problem I see in checking palindromes on the Internet is when the user inputs a palindrome sentence or phrase and the program returns a wrong output. So for me, I tried to optimize palindrome checking by accepting sentences as input.
import java.io.*;
public class PalindromeCheck{
public static void mai... |
I would like to compress a Magento HTML page using some regex, and this is what I have written:
function html_compress($string){
global $idarray;
$idarray=array();
//Replace PRE and TEXTAREA tags
$search=array(
'@(<)\s*?(pre\b[^>]*?)(>)([\s\S]*?)(<)\s*(/\s*?pre\s*?)(>)@', //Find ... |
Our task was to calculate the entry of a Pascal’s triangle with a given row and column recursively. The triangle was specified in a way that the tip of the triangle is column = 0 and row = 0. That said, column 0 has always the entry 1.
My concerns are that the way I initialize the triangle as an array and filling in th... |
Working on a project, I've taken to adapting the linenoise line editing library for my own use, among other things, rewriting it using C++. The idea is to separate my changes and updates into a new library, and publish it on GitHub, as one does. But before I release my changes into the wild, I'd like to ensure that it ... |
The previous and initial iteration at MSD radix sort in Java for parallel arrays.
Changes:
Entry hides both the sort key and satellite datum in private final fields. Henceforth, they are accessed through a pair of getters.
sortTopImpl is removed and replaced by sortImpl, which now can handle the sign bit as well.
comp... |
The problem comes from codility, whose coding problems I'm starting to enjoy as their evaluation criteria really looks at runtime.
Task description
A non-empty zero-indexed array A consisting of N integers is
given. The consecutive elements of array A represent consecutive
cars on a road.
Array A contains only 0s... |
I am writing a couple of functions accepting tables as input parameters. These tables constitute a range of options, which should either be given or inferred from default tables.
Concrete use cases can be found in the unit tests below.
The main question:
Is the code idiomatic Lua – especially the use of metatables?
Cod... |
How can I improve this game?
#include <iomanip>
#include <iostream>
#include <vector>
#include <random>
#include <conio.h>
struct Random
{
Random(int min, int max)
: mUniformDistribution(min, max)
{}
int operator()()
{
return mUniformDistribution(mEngine);
}
std::default_rand... |
I wrote these two methods to calculate the square of a number:
static int sqr(int val)
{
int valSqr = 0;
for (int i = 0; i < val; i++)
valSqr += val;
return valSqr;
}
static int sqr(int val)
{
int valSqr = 0;
for (int i = 0, j = 1; i < val; i++, j += 2)
valSqr += j;
return v... |
I have this parallel implementation of MSD radix sort, which processes the entries by one particular byte. At each byte index, it has three phases:
Count the bucket sizes.
Insert each entry to its bucket.
Recur on each resulting bucket, if there are less-significant bytes to process.
The only synchronization primitiv... |
I've written this script as a basic authentication system for use on Google App Engine. I would appreciate it if anyone would mind having a look and seeing if there are any obvious security vulnerabilities.
Overview
The whole thing is an API so obviously there will be a client (probably written in JavaScript) which wil... |
I recently wrote this code as a more versatile stand-in for Convert.ChangeType. I have a nagging feeling that there's something I might be overlooking, or that there might be a more efficient algorithm for this.
/// <summary>
/// Returns an object of type <typeparamref name="T"/> whose value is equivalent t... |
I needed a simple data structure to cache the most recent few directory contents for this project I was working on. I thought a linked hash map would be the right approach since we will cache only one item per path (the key) and keep only X recent items. We will store the timestamp and directory contents as the "payloa... |
I am fairly new to this, so please tell me whether this is a good way to write code or if I'm missing anything.
import ehs.*;
import java.util.Scanner;
public class blackjack
{
public static void main(String[] args)
{
BlackJack();
}
public static void BlackJack()
{
boolean again;
int money = money();
int che... |
I am coding a game, and I need to detect the color of a rectangles on a canvas, by moving a character and touching them, so that a message will be displayed "this is magenta" and so on. Please find below the game and my coding, so that you will better understand me:
jsFiddle
var canvas = document.getElementById("canva... |
I implemented a search function like this:
private static void GetResults(ref ObservableCollection<string> resultTitles, ref string[] query, ref ObservableCollection<int> weight)
{
int position = -1;
foreach (string[] r in SearchKeys.Keys)
{
position++;
foreach (string s in query)
{... |
Previous question:
Text-based Tetris game
I don't have a Linux terminal to be sure whether or not I have implemented the Linux version correctly, but hopefully it's OK.
Summary of improvements:
More OOP
Improved the names of the classes and their functions and I hope they're OK now
More portable, isolated platform-s... |
I finally managed to work with socket.io namespace stuff which I'm using for building a chat module. Here, employees of multiple organizations can join and vhat with other employees of the respective organization. What I'm doing at here is creating separate namespaces for each organization. So, it'll be easier for me t... |
As of now this game only consists of:
Splash Screen
MainMenu
SubMenus
Did I apply bad practices, or did I do something well? Is there a better way to do it?
#include <iostream>
#include <fstream>///filestream lib-- needed for file i/o
#include <windows.h>///Needed for alt clear screen function
#include <iomanip>///se... |
I need to HTML table output like:
<table>
<tr>
<td>ITEM<td>
<td>ITEM<td>
<td>ITEM<td>
</tr>
</table>
<table>
<tr>
<td>ITEM<td>
<td>ITEM<td>
<td>ITEM<td>
</tr>
</table>
<table>
<tr>
<td>ITEM<td>
<td>ITEM<td>
<td>ITEM<td>
</tr>
</table>
My code before:
<?php $i = 1;?>
<?php foreach ... |
I have solved Piggy-Bank problem on SPOJ using dynamic programming.
The question asks you to get the minimum value that is possible with given weight (\$w\$) and one or more coins (\$n\$) with given value, \$value[j]\$ and weight, \$weight[j]\$.
I am using following recurrence relation (zero indexed) to solve the prob... |
to_convert_files = [FileEnc(filename, getEncoding(filename)) for
filename in filenames if getEncoding(filename) != None]
The problem here is that getEncoding gets called twice for each accepted file name: once in the if clause and once in the expression preceding for. I know I can avoid this by spl... |
CKLinkedList is the implementation of a doubly linked list. I'd like to see comments on the memory management (I'm using ARC in the code below) and formatting + overall style.
CKList protocol file:
//
// CKList.h
// CollectionsKit
//
// Created by Igor Rastvorov on 11/30/14.
// Copyright (c) 2014 Igor Rastvorov. Al... |
This class is designed to call a similar function of multiple objects of multiple classes using a single interface (it is not for calling functions that return a value).
A potential usage will be sending same data to multiple writers (log writer, HTML generator and styled printer to console).
Tested with Python 3.4.2
... |
I've been learning NodeJS recently, and have a small program to get the external IP address on my home network from fugal.net, compare it to the previous IP address, and if there is a change update the stored version, and send an email with the new IP.
I'm running node 0.11.12 on a Raspberry Pi, and storing on mongodb... |
In an effort to learn more about AngularJS directives, I decided to create a simple, edit-in-place directive. I built a simple directive that would display a value, along with an edit link and the edit link would toggle visibility of an input and the save/cancel links. From there, I wanted a setup where I could make mu... |
In the Red5 server we have no control over what implementers do with their applications. As such, we have attempted to implement code that would prevent them from causing bad things to happen.
This class shows the creation of the task when a message comes in from a client:
ReceivedMessageTask task = new ReceivedMessage... |
I have this method:
public async Task<ActionResult> Index()
{
var orders = await db.Orders.AsNoTracking().GroupBy(x => x.Status).Select(g => new { Status = g.Key, Count = g.Count() }).ToDictionaryAsync(x => x.Status, x => x.Count);
ViewBag.InWork = orders[WebApplication.Models.Order.OrderStatus.... |
I made a mergesort implementation based on this code. Please review my C++ version.
using size = std::size_t;
template<typename T>
void merge(std::vector<T>& v, size low, size mid, size high) {
size i = low, j = mid+1;
std::vector<T> old{v};
for (size x = low; x <= high; ++x) {
if (i > mid) {
... |
In my data frame I assign values to the column Register by checking another column (Source) for specific values. Based on those values, the output in Register changes.
I am relatively new to R, but I have some coding knowledge. The following code contains lines that are all so similar that I can't help but wonder if it... |
I have the following struct:
public struct VolumeIssue
{
public readonly string Volume;
public readonly string Issue;
public VolumeIssue(string volume, string issue)
{
this.Volume = volume;
this.Issue = issue;
}
public bool IsNullOrWhiteSpace()
{
return string.IsNu... |
I'm trying to make controllers skinny as possible. I use repositories for accessing the database and I use Services to do other stuff. In this case, I use it to insert a new post to the database. For validation I use Jeffery Way's validation package for Laravel.
PostController.php
<?php
use Laracasts\Validation\FormVa... |
I've created a responsive nav but feel there's probably a more simpler way of doing it.
HTML
<header>
<a href="#" class="menu-toggle">toggle</a>
<nav class="main-nav">
<ul>
<li>Link</li>
<li>Link</li>
<li>Link</li>
<li>Link</li>
<li>Link</li>
... |
I've got some pages that may or may not load with a ReturnUrl parameter, and some links that will be generated without that parameter (though I've applied a class to them).
The site uses jQuery, and I think I've found the most elegant and least breaky solution as follows:
$(document).ready(function() {
$('a.my_retu... |
I quickly wanted a script that'll go through a lot of photos in a folder and only keep one photo per minute (gotta love burst shots on iPhone).
Fortunately, Dropbox names them with a timestamp upon import: I was thus allowed to base this one on the filename (an example filename is '2013-11-06 23.32.19 XXXXXX.jpg').
I w... |
I have a bash script that reads a config file with key/value pairs and uses these values to modify the functioning of other scripts correspondingly.
Example .cfg file:
layout='true'
code_compliance='true'
....
....
variablename='false'
output='true'
The file consists of a very less amount of lines currently but ther... |
A followup question can be found here, based on this question and it's answer.
Considering:
Interlocked.CompareExchange generates a memory barrier,
Intended to be used with very fast operations (like generating an
id),
SpinWait starts sleeping in milliseconds after 10 or so spins (and
does some other smart stuff),
Wh... |
I have a Ruby function which generates and saves a report. I'm looking for a Clean Code way of writing this:
def generate
violations = relevant_violations
comments = convert_to_cleaned_up_comments(violations)
text = convert_to_text(comments)
save_to_file(text)
end
But I hate single-use low-semantic-value var... |
I am trying to create a unique name for my uploaded images. It works, but I wonder whether I should make a few changes or not.
HTML
<form action="upload.php" method="post" enctype="multipart/form-data" name="uploadform">
<input type="hidden" name="MAX_FILE_SIZE" value="350000">
<input name="picture"... |
I have the following problem:
The stepping number:
A number is called a stepping number if every adjacent digits, except those separated by commas, differ by 1. A stepping number can't be a 1-digit number, it must be at least a 2-digit number. For example, 45 and 8,343,545 are stepping numbers.
But, 890,098 is not.... |
I wrote this simple solution about FizzBuzz. Is there any possible way to solve or optimize the solution, such as with bitwise tricks?
public class FizzBuzz{
public static void main(String[] args){
for(int i = 1 ; i <= 100 ; ++i){
if(i % (5*3) == 0){
System.out.println("FizzBuzz");
}else if(i... |
I'm working on a login system in Go (Golang). Previously, I was using Gorilla Sessions for this, but I wanted to see if I could reinvent the wheel and make it simpler.
Also, I don't need to store many user values—just one: whether a user is logged in or not. For this, I decided to use a map.
sessions := make(map[string... |
Takes the first array in the array and uses that to set the properties of an array-object.
var _ = require("underscore");
function csvToObject(data){
var header = data.shift();
return _.map(data, function(row){
var temp = {};
_.each(row, function(cell, key){
temp[header[key]] = cell;
});
retur... |
I've started with a bunch of functions, made the code work, then I spent a day rewriting it in an OO way, as much as I can.
I've tried to group up the task into objects, letting the relative data go to the relative function. But it still doesn't sound like OO, just several groups of functions.
There is an 'upload attac... |
I have following data structure
>>> a = [{'id': 1, 'name': 'a'}, {'id': 2, 'name': 'b'}]
>>> b = [{'id': 1, 'age': 12}, {'id': 2, 'age': 21}]
I want to merge the dictionaries present in list b with list a by matching id. (a and b have the same number of entries, but the order can be different.)
So I want following:
[... |
I recently started work on a game project, and decided to use GLFW for windowing / OpenGL context handling. GLFW doesn't have support for creating message boxes / dialogs, and I was unable to find anything simple online to do the job, so I decided to take a shot at creating a library to do so.
I've completed a first it... |
I implement the following algorithm in order to find a point from a given X value in a sorted list with the same distance between each X values. Here's an example of my list content with a delta of 10:
(687;10)
(12;20)
(24;30)
(10125;40)
(0;50)
(111;60)
(-2;70)
The delta can be any float number;
The list can be up to... |
The original question can be found here.
I implemented method 2:
Please comment about style, unit testing, code complexity, time and memory space and complexity.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
publi... |
This is a followup to a previous question.
Considering:
Interlocked.CompareExchange generates a memory barrier,
Intended to be used with very fast operations (like generating an
id),
SpinWait starts sleeping in milliseconds after 10 or so spins (and
does some other smart stuff),
What are characteristics (pros & cons)... |
I'm implementing a module system into one of mine ASP.NET MVC applications and I am currently writing a module helper which all the modules can use to get some basic information about itself.
I'm using the namespace of the caller to identify the module and search it up in the database and retrieve the information.
Now ... |
I may get a Map of many many items that needs to be requested to an API.
In order to improve performance, I thought about splitting that list into smaller sublists, and querying the API with this small subset.
For that, I came to this code and was wondering what was your opinion on it.
This is some banal initiator I us... |
The original source code by falgon.
For kbhit() and getch() in Linux/UNIX is written by Chris Giese.
Previous question:
Text-based Tetris game - follow-up
Summary of improvements:
More "magic numbers" eliminated
Deleted unnecessary classes
Implemented the elimination of a complete row if formed
How can I improve this... |
I am new to Python and am looking for any feedback/criticism on scripts I have written for work. This script works as I intended, creating multiple .xls files from a workbook with multiple worksheets. I'm just looking to develop a better understanding of how to use Python. So, please, feel free to rip in to what I've... |
I'm trying to implement a blocking counter that may have several readers and writers at the same time:
class BlockingCounter {
public:
BlockingCounter(int count) : count_(count) {
// init lock_;
}
~BlockingCounter() {
// destroy lock_;
}
void Increment() {
pthread_rwlock_wrl... |
I decided to implement a random walk.
The rules
The rules are easy, an object is moved in the direction dictated by random or pseudo-random numbers.
If you want to read more about it, see the Wikipedia Page.
A simple example
Let's say we decide:
1 = "Go right"
2 = "Go down"
3 = "Go left"
4 = "Go up"
We then generat... |
I took some code and reviewed it, but it got me thinking, so I re wrote the code a little bit and would like to ask what you think of it and why it's bad to do this, even though it works.
public class FizzBuzz{
public static void main(String[] args){
for(int i = 1 ; i < 101; i++)
if(i % (5*3) ==... |
The code works and I get the results I want. Please comment about complexity, a shorter way of implementing the solution, and advice for better unit tests.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
public clas... |
While I'm not new to Python, this is my first 'bigger' Python program I created, also my first game in Python.
import random
DEBUG = False; # If set to true, displays chosen word before each game. For debugging and cheating only :)
DICT_FILE = "english.txt";
GUESSES = 10;
def prompt(s):
while True:
an... |
I have a spinner in my activity that upon selection of one of it's options needs to handle the addition of a new object to my Sqlite database. the following solution works but everything in it looks like one big hack.
My layout:
<Spinner
android:id="@+id/spnMachineManufacturer"
android:layout_width="@dimen/et_p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.