instruction stringlengths 71 71.9k |
|---|
I was bored, so I wrote something that could turn .wav files in to .bmps:
#include <stdio.h>
char bmp[12000029]; // Need 12000028 bits, 1 pixel is 3
// bits and table is 28 (1500^2 * 3 + 28)
int main() {
bmp[0] = 0x42; // Bitmap signature
bmp[1] = 0x4D; // 'BM'
bmp[2] = 0x1C; //
... |
This is my final attempt of making an efficient ResourceManager class, which takes care of allocating OpenGL objects (like Shader, Textures, Meshes, ...). It stores each resource in a unique_ptr and then distributes const pointers of that type, which I call "Observant pointers." They cannot be deleted because resource ... |
I'm attempting to make a builder pattern that makes sense and is practical for storing user data in a flexible way in a document database. The DB I chose is MongoDB, and I'm using its Java API throughout. I plan on replicating this kind of pattern once I have something that is decent.
This works, but feels a bit clunk... |
The Jaccard distance between two sets is the size of their intersection divided by the size of their union. For example, the distance between {1, 2, 3} and {2, 3, 4} is 2 ({2,3}) / 4 ({1,2,3,4}) = 0.5.
The Jaccard distance can be used for string similarity by slicing a string into word or character n-grams. For exampl... |
This is a follow up question to my previous question. I am trying to design a thread safe parameters class with only readable getters. Idea is it should be possible to initialize this class once with some parameters - and throughout app I should be able to query values. Deinitialization should also be possible.
Please ... |
I'm currently doing a project, requiring me to implement a CircularQueue data structure in C++:
template<typename Type> class CircularQueue {
template<typename Type> struct CQNode {
Type head;
CQNode* tail;
CQNode() {
this->head = NULL;
this->tail = NULL;
}
CQNode(Type head, CQNod... |
I have written a simple system to load plugins from files in Python 2.7, and I'd like to see if any of it can be improved upon.
vedo.py
from __future__ import absolute_import
import os.path
import inspect
from vedo.event_emitter import EventEmitter
from vedo import VedoPlugin
def _get_module_name(directory, filenam... |
I am trying to learn functional programming in JavaScript, and saw a little task on Twitter that I wanted to have a go at:
var durations = ["12:38", "6:36", "9:03", "8:34", "5:02", "6:54", "13:22", "4:41", "8:36", "21:58", "3:06", "10:46", "10:13", "12:54",
"14:00", "11:03", "16:03", "10:52", "24:53", "10:03", "11:49"... |
I have modelled the task of super market pricing as per the below task.
http://codekata.com/kata/kata01-supermarket-pricing/
Please review my code and suggest any improvements.
class Product
{
String Name; //Name of the product
int unit_price;
UnitType unit_type;
boolean groupOffer; //Is this produ... |
The user has two 2D input arrays A and B, and a given matrix S. He wants to apply a
complicated formula to these arrays row-wise to get C. Something like: $$C_i = f(S, A_i, B_i)$$
where f is some complicated function, implemented by the user. That is, the user wants to supply his complicated formula in terms of the ro... |
I would like to be reviewed on efficiency, style, and obviously if there is a bug I would like to know.
def findsum(a, n):
''' Find whether a consecutive array slice sums up to n '''
for i in range(len(a)):
j = i + 1
while j <= len(a):
if sum(a[i:j]) == n:
return True
j += 1
return Fal... |
I wanted to write a JavaScript function that checked for balanced braces. I'd be grateful for any feedback on correctness and style.
var invert = {
'}': '{',
']': '[',
')': '(',
};
/**
* Returns `true` if braces are balanced.
* `false` otherwise.
* Usage: `isBalanced('{{[(')`
*/
function isBalanced(st... |
My script pushes zeros to end of an int array. I'd like to be reviewed on efficiency, style, and obviously if there is a bug I would like to know.
def nonzero(a):
''' given an array of ints, push all zeros to the end '''
zeros = [0 for i in range(a.count(0))]
x = [ i for i in a if i != 0]
x.extend(zeros)
retu... |
Find 3 elements that sum to zero in an int array.. I would like to be reviewed on efficiency, style, and obviously if there is a bug I would like to know.
def sum_to_zero(a):
''' given an array of ints, find 3 elements that sum to 0 '''
for i in a:
for j in a[1:]:
for k in a[2:]:
if i + j + k ==... |
I intentionally avoided Python tools which would make this even more trivial. I would like to be reviewed on efficiency, style, and obviously if there is a bug I would like to know.
def unique_char(s):
''' Find first non-repeated char in a string '''
myDict = {}
first = len(s)
for c in s:
if c in myDict.ke... |
I wrote this program, and it does what it asks, but it's so big and ugly. What can I change?
Some examples:
a b c --->
5 1 12 a is between b and c
5 12 1 a is between c and b
5 5 2 there is no gap
This was in an example of a test that is supposed to be small, so that's why I'm asking if there is anoth... |
Recently, I submitted a project that simulates a barbershop-style problem; the task was to create a Hotel that contained guests, front-desk employees, and bellhops. Each of these were to be implemented with their respective Semaphores, with mutual exclusion being kept to a minimum if possible.
My code works as expected... |
I'm trying to figure out how to organize interfaces in my game to make future development easier, by making my code more modular.
Notice that my Rook class implements the IPlayer interface, which will move it left and right, but not up and down (I had to add that in seperate methods). My question is, should I make an ... |
Please let me know how I can make it better, especially with avoiding repetition without the need to replace the user guesses.
import java.util.Scanner;
public class Lottery {
static int guess[] = new int[3],actual[]= new int[3];
private static void aquireGuess()
{
Scanner keyboard = new Scanner(S... |
I'm fairly new to Clojure and looking to improve my use of the proper idioms, and make my code more readable. Here's the problem:
Read from standard input and produce the count of each word to standard output, sorted by word, with a single space between the word and the count. Sort the output by word. Words are A-Z on... |
I wrote this code a while back and I have recently been rewriting most of my code. I just to know if these methods can be improved. The ones that pop out to me are listed below; others don't matter as much.
Methods that need improving:
FilterInjectionChars
IsValidAlphaNumeric
FilterFigure
namespace Apple.Application... |
From what I've seen in other posts, if I actually know the unwanted characters, then I can do string.replace(). But in my case, any characters can appear in my input string, and I only want to keep the characters that I want (without messing up the order of course).
private string RemoveUnwantedChar(string input)
{
... |
I'm running the following code on quite large data frames. I've rewritten it for the iris dataset to make it reproducable.
I'm quite unexperienced with the apply functions and I find them a pain in the bum to apply them.
Is there any ways to drastically improve the performance of this process?
lmfit <- lm(iris$Petal.W... |
Currently, when I'm wanting to print a value for my class I do the following...
<%= @person.team.name if @person.team.present? %>
This seems really redundant to me. I've also have done...
<%= @person.team.name_display %>
where I've created a function for each attribute to kind of hide the first case. It seems a lit... |
I currently have this code to read lines from a file
def getLinesFromFile(filename):
content = []
# with open(filename, "r+") as file:
# for line in file:
# line = line.rstrip()
# if line:
# content.append(line)
file = None
try:
file = open(filename, "r+... |
Awhile ago I posted a Translator app that I have been in the process of making. I edited some features in it and I've decided to post it again.
My questions:
Is there anything I should add to this?
Is there any better (more easily readable) syntax for what I'm trying to do?
Say I wanted to make a GUI for this app. Wha... |
I'm new to Python/Programming and wrote this simple "Day of the week/Holiday finder" script. Ideally I'd use something so I can have a little widget on my desktop, but right now I'm looking for any and all suggestions to improve my code?
I'm importing this holiday module
import datetime
import holidays
today = datetim... |
This is a follow-up to this question.
Using his ExactCover class, I slightly modified Garth Rees' Alberi class to cope with regionless schemes and forced void cells:
"""Solver for an Alberi puzzle using exact cover
"""
from collections import Iterator
from itertools import product
from ExactCoverExt import ExactCover
... |
Is there a better way to optimize this code? It started with \$O(n^2)\$ (nested loops) then \$O(n)\$ (with index).
public static String getRelativePath(String from, String to) {
String relative = "";
String regexPath = "/";
String regexLow = "..";
List<String> toList = Arrays.asList(to.split(regexPath)... |
I have a method in a Python app to write a list of records to a CSV file. Each record is a "football player", which is really just a dictionary. But one of the dictionary items contains a list of weekly scores. I want to write out to CSV a record for each player, and then flatten the list of scores and write that ou... |
Problem description:
You have two eggs, and need to find the maximum floor of a 100-floor building from which you can drop the eggs without them breaking. Do this with as few attempts as possible.
NB! You are passed the level of where it breaks, n, and an egg is considered broken when your compares and finds test floo... |
I was recently given an interview and was asked to write my own lock implementation using atomics, but not necessary reentrant.
I didn't answer the question, but at home, I wrote this code. Please asses my implementation and suggest better solutions.
public class MyLock {
AtomicBoolean locked = new AtomicBoolean(f... |
This is a simple wrapper class for a lambda expression, that stores one as Expression and hands it back out either as Expression, or compiled as Func. This is useful because while Linq-to-Objects requires a Func, other technologies such as Entity Framework require an Expression (so that the expression tree can be proje... |
I've been teaching myself C for the last few months. As a learning exercise, I set out to write an ncurses implementation of the classic card game Uno, mostly because it was was one of the simpler card games I could think of.
Since my emphasis in writing this was primarily learning concepts and algorithms, the interfa... |
I've written some code to solve the longest palindromic subsequence problem.
def memoize(f):
""" Function decorator used to cache results """
d = dict()
def inner(*args):
if args not in d:
d[args] = f(*args)
return d[args]
return inner
def max_palindrome(s):
""" Returns ... |
The following code gets video renditions from Brightcove using the media API. It then generates an ordered source list for the JW Player and selects the default rendition based on a pre-set bitrate.
function buildSourcesFromBrighcoveID(brightcoveID, onComplete) {
var sources = [];
var brightcoveAPI = 'http://ap... |
I recently watched a video course on groovy and started working on some of the Project euler problems to flex my groovy* muscle.
(This is problem #8)
The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832.
Find the thirteen adjacent digits in the 1000-digit number tha... |
For an exercise, I've written a function that, given an array of objects and a key (2nd argument), returns a new array of objects that contain all properties from a key. How'd I do?
function where(collection, source) {
var arr = [];
var keys = Object.keys(source);
var countMatchingProps = 0;
var currentProp... |
This relates to Round to specified int but I'm separating these methods out since they're technically different.
Is there a method that already performs a custom floor and ceiling to a specified integer?
// If the interval is 5, 9 --> 5.
public static int FloorTo(this int value, int interval)
{
var remainder = valu... |
I'm displaying multiple queries and if statements. In the if statement, it increments notice_category_id by 1 each time a category is created, but when I code the update/delete/edit (or if truncated), sections won't rowCount() increment the row and make duplicates. I'm just wondering if I should change the way the the ... |
Cardshifter is an online trading card game, made by a gang of Code Review community members. Cards can have a bunch of different, and sometimes complex effects, and descriptions for these are automatically generated if no custom one is given.
EIGHT IMMORTALS:
Choose 1 at random: Summon 1 Life Tool to your Battlefiel... |
I can see a possible performance optimization with declaring 2 arrays and iterating the $fake_widgets only once, but how else can I make the following conditional string building more elegant in Ruby?
pending_coloring = $fake_widgets.select do |widget|
widget[:status] == 'awaiting_coloring' && widget[:owner_color] =... |
I've created my first Android drawable, a hourglass shaped image, and I'm curious what can be improved with it. It seems weird having to use 4 paths, but I couldn't get it to work any other way.
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:wid... |
Curious what people think about this implementation of Conway's Game of Life in Haskell.
{-# LANGUAGE QuasiQuotes #-}
module Test.Conway (
conwayCalculateAge,
conwayStep,
conwayMakeRandom,
conwayMakeRandomIO,
conwayMakeEmpty
) where
import Data.Array.Repa
import Data.Array.Repa.Stencil... |
I am writing code that creates a hash for a store that has an item, price, and sku. The hash is inserted into an array. I also create another hash based on the sku that holds the amount of inventory for that item. I am new to Ruby and am looking for ways to improve my code.
class SimStore
def item_info
... |
I heard goto is bad, so I ask someone in this site if my code is better using goto or other alternative
public FormMain()
{
// start of the apps
Start:
// show login form
FormLogin login = new FormLogin();
DialogResult dr = login.ShowDialog();
// cancel form loading if ... |
I have been programming for a couple months now and really wanted to make my own game, so I chose battle ship due to is simplicity (I learned out how wrong I was). I know one thing I am going to hear about is that it isn't portable due to the fact I am using the windows library. All I have to say is I tried finding oth... |
This computes the integer square root at compile time for any \$0 \le N \le L\$ where \$L\$ is the largest integral representation of template parameter T.
This was motivated by the fact that many of the algorithms I found were not able to handle large values of \$N\$. I also just wanted to practice template meta-progr... |
This code creates a singleton event dispatcher. It's called like this:
eventDispatcher = Event()
eventDispatcher.on("event", handler)
eventDispatcher.trigger("event", 5)
I'm wondering if this is "the python way," or if it could be improved? Especially the class, I'm not sure about creating a new object for every use... |
Scenario: I have a main thread which spawns few child threads to do some independent tasks. After each child thread finishes their tasks, the main thread proceeds. The code I have written is working in most of the time. However, in case one of child thread gets blocked, the main thread has to wait for ever. As it is no... |
My tooltip works fine, but I need to simplify this code.
var genderSelect = {
getGenderSelect: function () {
if(this.val('Girl')){
$(this).find('#girl-character').show();
$(this).find('#boy-character').hide();
}else if(this.val('Boy')){
$(this).find('#boy-character').show();
$(this).f... |
The implementation of the algorithm which adds two number in string form with arithmetic rules.
var assert = require('assert');
var strAdd = function(lnum, rnum) {
lnum = lnum.split('').reverse();
rnum = rnum.split('').reverse();
var len = Math.max(lnum.length, rnum.length),
acc = 0,
res = [];
for(... |
I have created a ViewModel for a Product Edit page because it has specific related entities I need to load - the class currently looks like this:
public class ProductEditView
{
public ProductEditView(Product product)
{
this.ID = product.ID;
this.Code = product.Code;
this.ProductLanguage ... |
The new EcmaScript standard, ES6, contains specifications for Map and Set built-in classes. Each of these collections treats an object-valued key as opaque and unique, e.g.:
var foo = new Set();
foo.add({bar: "baz"}).has({bar: "baz"}) // == false
However, there are cases in which one might want to treat similar objec... |
I've recently finished writing a "simple-as-possible" LDA code in Python.
The theory from which I've developed my code can be found in the book Computer Vision by Simon Prince, free (courtesy of Simon Prince) pdf can be found on his website: http://computervisionmodels.com/ - Chapter 20 talks about LDA.
Applied to comp... |
I have a LINQ query that I am having trouble optimizing and takes about 5.5 seconds to run. I am using a view called StaffingResourceData and a table called StaffingForecasts.
Each StaffingResource has a ResourceId, a Division, and a Type. A StaffingForecast has a ResourceId, Project, Date (represents a Monday of a we... |
This implementation uses ECMA6 syntax and babel as transpiler. You can use this code to add integers which are bigger than Number.MAX_SAFE_INTEGER.
var _ = require('underscore'),
assert = require('assert');
var strAdd = function(lnum, rnum) {
var {rem, res} = _.chain(
_.zip(
lnum.split('').reverse(),
... |
This question presents two rather small Java programs: the first one is a simple client that reads text from command line and sends it to the server (TextSender.java); the server does nothing more but echoes the received text on the command line (TextReceiver.java)
TextSender.java:
import java.io.IOException;
import ja... |
My goal is to find the largest connected "cell" of 1's in a matrix.
My approach has been to search the surrounding area of a cell that is not on a border and then if it hasn't been visited, and has a value of 1, increment the group. I am absolutely sure that there are better, more recursive solutions out there, but I ... |
I want to know if there is any other better way to write this algorithm. What other data structures could be used to make it more simple and effective?
public class BubbleSort {
public static void bubbleSort(int array[]) {
int n = array.length;
int k;
for (int m = n; m >= 0;... |
So my code is done it outputs exactly what it needs to I'm just wondering if it is possible to make this code a lot more simple using objects. If so could someone tell me what I would need member-wise and I will try and implement it. When I tried it got way too complex and it ended up looking easier to just write funct... |
I recently read the book clean code by Robert C. Martin and I'm trying to apply his style of writing methods to the FizzBuzz programming example.
So far I have two "public" methods called: start and parseNumber, that respectively start the FizzBuzz program or parse a single number according to the FizzBuzz principle.
c... |
It seems there are a lot of "empty containers" (I do not know the correct, technical term) with regards to multiple levels of abstract classes and functional interfaces with little or no code. Is this the case in real working situations?
Here's the class diagram:
And here's the code:
package shapeHierarchy;
public ... |
The following problem is currently taking more than 8 seconds to execute. Please help me to modify the program, so that execution time will be reduced.
var yourself = {
fibonacci : function(n) {
if (n === 0) {
return 0;
}
if (n === 1) {
return 1;
}
else {
return this.fibonacc... |
BitPat here is a wrapper around a bitset.
class BitPat
{
private:
boost::dynamic_bitset<> data;
public:
bool BitPat::operator[](size_t coord) const
{
if(coord < length)
return data[coord];
else
throw std::out_of_range(std::string("Pattern coord out of range")
... |
I wrote a short Haskell script to compress and decompress via the use of run length encoding.
The concept is simple enough, n equal items x in a row will be replaced by (n, x), decompressing is just the reverse.
For example:
> runLengthCompress "foooo barrr"
[(1,'f'),(4,'o'),(1,' '),(1,'b'),(1,'a'),(3,'r')]
As you can... |
Because I don't like writing the same useless exeption messages all the time ;-) I thought I create a better exception that would make this for me. This is what I came up with:
[Serializable]
public class SmartException : Exception
{
private const string PropertyNamePrefix = "$";
private const string InnerExcep... |
Once more, I come to you for assistance! I have written a significant bit of code that converts IP Addresses from strings to minimal byte-arrays. (So that you can store them in a binary format instead of as a wasteful string.)
It currently works with IPv4 and IPv6 addresses, saving both to a 16-element byte-array. (The... |
This program is working correctly, but I need to check if the structure is good or can be improved. Plus, if I called ra.area() immediately after declaring ra, I get 687194768. Why is that?
#include "stdafx.h"
#include "iostream"
using namespace std;
class rectangleclass
{
int w,h;
public:
void setnum(int x, int y)
{
... |
I'm trying to develop a lightweight enum for Python 2.7. This question is downstream of the SO question here; for context, a streamlined version of the bulleted addendum to that question is replicated below:
My desired feature set is:
Only having to type the enum name (or value) once in the source definition.
Valid ... |
The module adds syntactic sugar to Python 3 to allow concise specification of templates. I use it to generate a collection of static web pages from various data sources.
I wanted something relatively simple without the overhead of, say, cheetah or more recent templating systems (e.g. Mako and Jinja2). (I don't want t... |
import itertools
def permutation_lib(iterable):
return itertools.permutations(iterable)
def permutation(iterable):
if len(iterable) <= 1:
yield tuple(iterable)
else:
for sequence in permutation(iterable[:-1]):
for i in range(len(sequence)+1):
yield insert_at(se... |
After posting my first question on here, I got a lot of great feedback. I've decided to try another challenge and write it as cleanly as possible.
The rules of Odd-Even consists of the following tasks:
Given a max number a string should be returned counting up to and including that max number and adhere to the followi... |
I've written an A* search to find the optimal solution to the equation
$$ \dfrac{4}{n} = \dfrac{1}{x} + \dfrac{1}{y} + \dfrac{1}{z} $$
with \$n, x, y, z\$ positive integers, and \$n\$ given; the optimal solution being the one with smallest sum \$ x + y + z \$.
(The Erdős–Straus conjecture states that there are solution... |
I have some data under an HTML format and would like to import it in R. However, it seems that type inference is much less sophisticated than what exists with functions such as read.table. I am using the following workaround, which consists in reading the data table once, write it as a csv and re-import it.
# import r... |
Background:
I'm in the process of writing a relatively simple behavior tree driven AI system for a game that I'm working on. Basically, the behavior tree is made up of individual gameplay tasks (move, attack, etc.) as well as composite tasks that iterate over sub-tasks in a variety of ways. Each gameplay task is a leaf... |
(Offtopic note: I can't add a "networkx" tag.)
I reworked an old algorithm, this time not implementing the graph on my own, but building on the networkx module.
Script works fine for the tests and the small test file, but takes forever (estimated at around 8 hours) on the large file.
I had trouble breaking the progra... |
I'm trying to learn C++ again, trying to do all the "modern" stuff (e.g., avoid pointers in favor of references) and I found that I have some trouble understanding how references and lifetimes work. I'm using clang with -std=c++11.
I want to have a RAII-class, RoomList that basically wraps a map<int, Room>. On construc... |
This class is my attempt at creating a re-usable class that simplifies the parallel calculation of products. I would appreciate hints on all aspects especially the value of the threshold for which the best performance is obtained.
import java.math.BigInteger;
import java.util.concurrent.RecursiveTask;
import static ja... |
I have the following js code and am wondering how I can make it clean. It works fine but there are few repetitions. Is there a way to make it more clean?
$('.js-decline-button').click(function() {
$('.js-confirmation').show().stop(true).animate({ left : '0' }, 500);
});
$('.js-confirmation-yes').click(function()... |
I'm getting these errors:
error C2512: 'course' : no appropriate default constructor available
error C2374: 'co' : redefinition; multiple initialization
#include <stdafx.h>
#include <iostream>
#include <string>
using namespace std;
class course
{
string coursename;
int courseid;
int passinggrade;
publ... |
I ported a lz77 implementation from java to c#, and it's working fine. Now I want it to compress bytes and not strings, as I need it for another project.
This is the porting, operating on string:
public class StringLZ77
{
private char _referencePrefix;
private int _referenceIntBase;
private int _referenceIn... |
I have a date control which has a dropdown for each date, month and year.
The issue is, I can select 31st Nov. 2015 as well, and when I create date object, I get 1st Dec. 2015.
Example
var _date = 31; // value fetched from dropdown
var _month = 10;
var _year = 2015;
var date = new Date(_year, _month, _date);
docum... |
I have an application that has a form. Validation and data insertion works fine. However, it bulks out my controller. I've always been told skinny controllers.
For example:
class myController extends BaseController
{
public function store(myRequest $request)
{
$company_id = Company::insertGetId([
... |
I've been writing a python script to help me clear up some files that contain outdated code, while also serving as a way to learn python. These files have sections of code surrounded with tags on their own lines, I need it to remove both the tags and everything within. While this largely applies to XML documents I am a... |
I decided to make a Breakout game in JavaScript. Is there a way of making it cleaner? For instance, creating objects for the ball and the paddle.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Brick Game</title>
<style type="text/css">
body {
background-color: black;
}
canvas {
... |
The following should read a hex string such as "ece998a2fb" into vector 236 233 152 162 251. I was unable to find any built in method for doing this.
as.byte.vector <- function(hex.string) {
vapply(seq(to=nchar(hex.string), by=2), function(idx) {
as.numeric(paste("0x", substr(hex.string, idx, idx+1), sep=''))
}... |
I created various functions for string manipulation in Lua, where the strings are composed of tokens separated by an ASCII character (which may be the point, comma, semicolon etc.). One of these is the function puttok()
local function tokenize(C, strng)
local sInput = strng or ""
local sChar = string.format('%c... |
I would like to represent a numeric range in C#. Either open-ended, such as "up to 35" or "100 on up" or closed-ended, such as "34 to 65". I'd like to represent the open end with NULL. Further, I'd like to parse strings into the range. Strings will look like "-35", "100+", "34-65" or even "-10.5--0.5". I hate that the ... |
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace Common.Extensions
{
/// <summary>
/// Contains the logic for streaming extensions.
/// </summary>
public static class StreamExtensions
{
/// <summary>
/// Serialize an object.
///... |
I have one window service. At any given time this window service runs 5-10 threads and each thread do some logging on text file. Logging can be exception or some information related to task/job. I have to make sure all the log should be in sequence with date and time. This is so important. Log file should create every ... |
I need to call this function over a big dataset. I need it to be as efficient as possible but still be readable. Can I make it anymore efficient by using a different function for capitalize or blank check?
public static String nameFormat(String title, String firstname, String lastName) {
if (StringUtils.isBlank(fi... |
Currently, I'm writing a program that encrypts/decrypts text using Caesars cipher. The code below shifts a character.
/// <param name="originalChar"> char to shift </param>
/// <param name="shift"> amount to shift by </param>
/// <param name="letterA"> letter A in ASCII </param>
/// <param name="letter... |
So, I have a memory game written, but was wondering how I could turn these letters in the cardSet into images (I have a set of images in an images folder within the folder containing this code, called cat.png, cow.png, etc). Here's the js:
$(document).ready(function () {
var cardSet = ["A", "A", "B", "B", "C", "C",... |
This might not even warrant posting here, but I"m enjoying it and thought I would share.
//For Testing
function write_to_file($message){
$handle = fopen("/path/to/logs/a_log_file.php", "a+");
if (is_array($message)):
fwrite($handle, "\nMessage is array.\t ");
fclose($handle);
... |
This program runs in about 1.65 seconds on a 1.65GHz dual core processor.
I compile it with:
gcc -Wall -o ./program ./program.c -lm
Are there any optimizations I can use to speed this up, or is it already going about as fast as possible on this machine?
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include... |
I made a genetic search algorithm in Python for the Travelling Salesman Problem for a midterm project. The grade was fine, but I was hoping to get some pointers on style and documentation. Please provie any feedback you have about how I can make my code more readable, consistent, and friendly.
"""
geneticTS.py
By Loga... |
I've implemented the classic game Rock Paper Scissors with scores, and a save file implementation. I'm looking particularly for ways to get rid of all the self.'s. Is there anything I should add, remove, or change. Are there any bugs? Anything else?
#Programmer:
import random as ran
import shelve
class Score(object):... |
I'm a new programmer, who has just finished his first small project.
It's a sort of basic imitation of the grep command from Linux. I'm learning from projects the hard way. Here is the description of the project:
The first project that we’ll try is called logfind. It’s nothing more than a simple version of grep so yo... |
I wrote a tool to send emails with data saved in excel spreadsheets (.xlsx).
It uses the openpyxl module to interact with the spreadsheets and smtplib to send the mails.
It is only tested with (and should only run for) xlsx files generated by google spreadsheets.
It should work with everything openpyxl is supporting, b... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.