instruction stringlengths 71 71.9k |
|---|
Building a 'card' database: I'm simply learning to take input data and store to database. Incorporating JSON, PDO, SQL, and enforcing my general coding skills through PHP, hopefully.
$query = $dbh->prepare("SELECT * FROM " . $table);
$query->execute();
$result = $query->fetchAll(PDO::FETCH_CLASS);
$temp = array();
$d... |
I've written this code in an attempt to create the Monty Hall problem and check the ratios. I would like someone to check the logic on it. I know it isn't organized well at all; I just need to see if I'm performing correctly.
If you don't know what the Monty Hall problem is.
private static int losses = 0;
private stati... |
I've made a working calendar program, BUT I believe it's extremely inefficient. I think I have way too many else if statements:
import java.util.*;
public class MyOwnCalendar {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the number ... |
Using the Flat Web Design Tutorial offered at 1webdesigner I tried converting the resulting PSD file to HTML5 and CSS3. While attempting to use sectioning elements in the markup I quickly found myself lost in how to maintain semantic code while also adhering to the original design. As a result there are more div tags t... |
I wanted to write a human readable datetime.timedelta that can be used in log files.
Eg, "Report issued 1 hour, 44 minutes, 20 seconds ago"
I noticed that casting a timedelta to str() generates something almost like what I want, but not quite.
To this end I wrote this:
def verbose_timedelta(delta):
hours, remainder... |
I've some classes (Derived1, Derived2, etc.) derived from class Base. All of derived classes have a following methods (reduced sample):
void Derived1::handleTimer(const StatusType &st) {
if (!st.isOk()) {
m_timer->WakeUpPeriod(10); // wait for 10 seconds;
m_timer->SetHandler(boost::bind(Derived1::handleTimer,... |
I am trying to import a .csv file, clean the contents, and make sure all the errors are eliminated.
IO error
file format error
data error
I am using the snippet below. Could someone help me clean it and make it more pythonic?
try:
fl = request.FILES['csv']
except:
return HttpResponse("Some IO Error")
try: ... |
I'm working on a website on ASP.NET MVC4 and EF5. I want to ensure that only modified values are updated in the database. I'm using a unit of work pattern and repositories for data work. Here's the code for a generic repository. I've two questions, and need a code review for the following code.
Is the code to update ... |
I have many small but similar classes like these:
class DepartmentSerializer < Serializer
self.root = false
attributes :id, :name
has_many :employees, serializer: EmployeeSerializer
has_one :location, serializer: LocationNameSerializer
end
class DepartmentWithManagersSerializer < Serializer
self.root = false... |
The specific issue is this: I am writing to a file and want to output a new line after each line written. If I use a normal loop without any further checks, this will create a blank line at the very end of the file for no reason. So I need to do this every time except the last one.
Despite the fact that this is a spe... |
I have this JavaFX code which is used for listing groups by ID and name:
import java.util.List;
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ListCel... |
Basically, this function returns a list of flights for an airline. But if the airline doesn't exist, I want to throw some custom runtime exception. If that airline does exist, I want to return a list of flights (which could potentially be empty).
Is this is the standard way of doing things in Scala, or is there a bette... |
In my code I declared a dictionary to store various counters
let counters = Dictionary<Type, int>()
Later, I need to generate several labels using these counters, like this:
First type a label is generated for a given type, it should consist of the type name itself:
"MyType"
Subsequent label should be the type name, ... |
I'm starting with object oriented programming, but I know PHP procedural style "pretty well" I'd say. I'm working on a ticket support site for this website.
This mysqliSingleton class was in a question I previously visited. I only added the set_charset() method to feet my database. By the way, should that line be in th... |
I have a concept of the user having many API keys, but the API key belongs to the user, so I did the following:
config/routes.rb
resources :users do
resources :api_keys, path: '/developmentcenter'
end
app/models/api_key.rb
class ApiKey < ActiveRecord::Base
belongs_to :user
end
app/controllers/api_keys.rb
No... |
This Caesar cipher can take any integer and it will wrap around the correct number of times and still perform the encryption/decryption.
Let's say we have a text file named dog.
~$ cat dog
The quick brown fox jumps over the lazy dog...
If the user enters a normal offset (1-26), it will perform like any other Caesa... |
I have written a simple desk accessory in Proccessing called Trip, you can see it below. It is working, but it is very simple, and needs more features.
import processing.pdf.*;
PImage tardis;
int flash = 0;
void setup() {
size(256, 256);
frame.setResizable(true);
tardis = loadImage("TARDIS1.jpg");
beginRecord... |
Is this a good C program for splitting a command line without doing any expansion on it? Don't worry too much about main() and the output -- those are for testing.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <assert.h>
void pullwhitespace(char **input);
int main (int argc, cha... |
Here's my attempt at Weekend Challenge #3.
Key characteristics of this Python entry are:
The strategy is to alternate between "auto-complete" (making simple deductions such as naked singles and hidden singles) and recursive guessing.
The puzzle state is stored in a Sudoku object, which has a mutable 2D array. Unknown... |
I have a small program which makes uses of pycparser to parse C header files. The code, unfortunately, kinda sprawls out everywhere to handle the different cases (example below).
What's the best way to make this more Pythonic? I thought about case-statements, but those don't exist in Python. Is splitting the function i... |
I am writing a cron job to manipulate and transfer remote data.
I need to cache data from a table, process it, merge with previous table, iterate the process, and eventually send the result data to remote database.
Here is a basic in-memory cache storage with thin simple CRUD type API.
It has to store hashes, enforce e... |
#!/usr/bin/python3
# Description: Python script that will mount FTP-Server via SSHFS protocol
import sys
import os
import subprocess
def mount():
#Function for mounting the networked drive
if os.path.exists('/home/user/MNT/MEDIA/'):
print('Network drive is mounted')
un = input("To unmount type U... |
I would like to increase my performance of js code write a clean code... can you tell me how to do it... providing my fiddle below with js code...
http://jsfiddle.net/YYg8U/
var myNumbersToSort = [-1, 2, -3, 4, 0.3, -0.001];
function getClosestToZero(numberSet) {
var i = 0, positiveSet = [], positiveClosest = 0;
... |
I have this code:
switch (c) {
case '-': break;
case '0': e = expr(j).reduce(C1); e=not(e); a = and(a, e); break;
case '1': e = expr(j).reduce(C1); a = and(a, e); break;
default: throw new Exception("Unexpected cube value, " + c);
}
The cases 0 and 1 are only different by not. I do not like to encode t... |
I have to reverse the string "He is the one" to "one the is He". I have written some programs in Java but am looking for other best solutions. Suggest any possible ways to minimize the current program.
First approach:
class StringRev{
public static void main(String args[]){
String str = "He is the one";
S... |
I have an image loader, now only for bitmaps. I'm a little confused because I want to split my code to different classes, one for writing a BMP data to a file (WRITER), one for loading BMP data from file, or from pre-generated dataset (1) and storing it in its private members.( (1) like a noise function saved to an arr... |
I am writing a flask app that I will deploy it on Heroku to test it. There is a page that will generate daily photos and information based on a JSON file. The view is valid for 24 hours beginning from 00:00 to 23:59 of everyday.
I am thinking about using a cache, otherwise the app will consume unnecessary resources.
im... |
I'm trying to make a scala interface to the spotify API. I'm using it to learn Scala. I come from mostly a python background.
import dispatch._, Defaults._
trait Request {
val name: String
val endpoint: String
}
case class Track(name: String) extends Request {
override val endpoint = "track.json"
}
case class ... |
How would one optimize this code?
import java.util.*;
public class VendingMachineAssignement {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double item1 = 1.25;
double item2 = .75;
double item3 = .90;
double item4 = .75;
doubl... |
I'm building an http handler at work which has about 6 methods and I'm trying to figure out what design pattern will work the best for my needs:
What's done already (Only an example to make this more clear, methods are not real, but the main concept is there):
#region interfaces
public interface IDateRange
{
DateTi... |
Does my PHP look secure enough for a sign up form?
<?php
$con=mysqli_connect("host","user","password","db_name");
$sql="INSERT INTO users values (?, ?, ?)";
if ($stmt = mysqli_prepare($con,$sql)) {
mysqli_stmt_bind_param($stmt, "sss",
$_POST["username"], $_POST["pwd"], $_POST["email"]);
if (mysqli_stmt_execute... |
Is there a more optimal way of retrieving the character for the letter? I would assume that I would just replace my Entry set loop with another map, but I do not want to bloat the code, because it will reduce scalability.
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class AciiLett... |
I'm creating a program to retrieve web content in order to learn how these things work. I would like it to be as correct as possible, ideally fully compliant.
But I'm not sure this is the right approach to the problem. Is the following structure an appropriate way to hold server response header data after parsing it?
t... |
Project Euler problem 9 says:
A Pythagorean triplet is a set of three natural numbers, a < b < c,
for which,
a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c =
1000. Find the product abc.
I am a beginner in programming, especially Python. I got... |
I am still new to C++ and don't have a great insight on my coding yet, so I would be very grateful to anyone and everyone that gives advice.
Also, this code is meant to: keep all of my objects in an ordered fashion based on depth. I have a couple functions that allow for easy management and I made object friends with t... |
Im creating an single page application with not reload or redirects so I display all my contents with partial view(since im using MVC4 and angularjs ) and modals.
But I came with a situation, and that is that in some cases when i request a view with ajax to the server I need to perform some action(javascript loads) on ... |
I would be glad if someone could take a look at my code and maybe improve it. It's an animation effect to gradually reveal text as if it were being decoded. I wouldn't mind if it could run with jQuery (if it's shorter or better). I uploaded it on jsbin.com. It's all about the effect and not about encryption or decrypti... |
This code works great, but I think it can be reduced.
@if (Session["Success"] != null)
{
<text>
<div class="alert alert-success">@Session["Success"]</div>
</text>
Session.Remove("Success");
}
else if (Session["Error"] != null)
{
<text>
<div class="alert alert-danger">@Session["Error"]</d... |
1. Introduction
This is a solution to Weekend Challenge #3: a Sudoku solver in Python. It works by translating a Sudoku puzzle into an exact cover problem, and then solving the exact cover problem using Donald Knuth's "Algorithm X". The code should be self-explanatory (assuming you've read and understood the Knuth pape... |
I am building a cypher program which uses a matrix of numbers and letters. A message is encoded according to the row and column each letter of the message is found in the matrix.
I am trying to find a nice way of iterating over the 2D matrix (6*6).
for char in range (0, len(message), 1):
for i in range(0, len(rows),... |
I have made an application to display images in the form of gallery, from terminal if you are standing at the same location then it will open those images in the gallery if it does not have it will prompt to select the directory.
below is the module: gallery.py
import sys
import os
import utils
from PyQt4 import QtGui... |
This is the problem and my solution to this is:
#include "iostream"
#include "stdio.h"
#include "algorithm"
#include "math.h"
#include "string.h"
#include "time.h"
#include "stdlib.h"
#include <list>
#include <vector>
#include <string>
#include <queue>
#define MALLOC(name,type,n) (name=(type*)malloc(sizeof(type)*(n)))
... |
I have a UIImage Category for iOS Objective-C which tints an image based on a given UIColor value. You can take a look at the method below:
- (UIImage *)tintImageWithTint:(UIColor *)color withIntensity:(float)alpha {
CGSize size = self.size;
UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen... |
I've seen usage of switch(true) multiple times and have used it myself today instead of multiple elseif`s. Here is the case I used it for:
var isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') != -1;
var isSafari = navigator.userAgent.toLowerCase().indexOf('safari') != -1;
var isFirefox = navigator.userAge... |
This is part of my attempt at the Week-End Challenge #3. The overall problem is larger than will fit in one question. This is a well-contained subset of my larger program.
The goal of this part is to brute-force all possible (if any) solutions to a puzzle. The input to this algorithm is a 2-dimensional array representi... |
I had this code lying around, so I figured I would submit this as my first attempt at a weekend-challenge. I would prefer if reviews contained suggestions on how to improve the algorithm, but all suggestions are acceptable.
#include <stdio.h>
int isAvailable(int puzzle[][9], int row, int col, int num)
{
int rowSt... |
This is my first, very-very first attempt at java. I haven't started tackling the actual resolution of the sudoku puzzle (not even sure where to start, haven't looked at other weekend-challenge entries yet). I don't have much to go over here, but I'm sure it's filled with beginner mistakes already, so before I make thi... |
This is a Python script that generates a grid of random HTML colors. It works by reading random data from /dev/urandom and then encoding it as a hexadecimal string. This string is spit into individual values that will be represented as a color.
I am wanting to know if this is the best way to generate random values fo... |
I have written ExtendedConfigParser class that adds ability to dot access config values like ExtendedConfigParser().section_name.option_name:
from ConfigParser import SafeConfigParser
class ExtendedConfigParser(SafeConfigParser):
def __init__(self, config_file=None, type_conversion={}, *args, **kwargs):
... |
Even though it's the first time I'm writing something this "big", it feels like I know C# quite well (it is very similar to Java after all). It's been nice to learn LINQ also and I am very impressed by the features (which is just like Steams in Java 8), and perhaps I have overused it here (if it's possible to do that).... |
I'm trying to figure out a way to have cleaner, efficient code for a web audio project i've been working on. the code I have right now is this:
//OSCILLATOR INFO//
// Oscillator Pitch is in Hz.
// Oscillator Detune is in Cents & can be positive or negative values.
// 1 Octave = double/half the note frequency in Hz. (A... |
I am building an array of strings to form the "empty" representation of a puzzle onto which I will overwrite single characters as necessary for debugging purposes. However, building the array using scalar multiplication results in shared string instances among the rows which breaks when I modify them.
> grid = [["... "... |
I'm writing a function in Python that compares the modification time of a file in Linux (using os.stat) with a specific time and compare the dates. If the modification date is older than the date I specified, an event should happen.
import os
import time
import datetime
# File Modification time in seconds since epoch... |
Original
quicksort.h
#include <algorithm>
namespace quicksort {
template <typename iterator, typename value_type>
struct traits
{
static iterator choose_pivot (iterator first, iterator last) {
return first + (last - first) / 2 ;
}
static iterator partition (iterator first, iterator last, iter... |
I have some concerns:
Is it normal for the class to have at least one node? In other words, this implementation cannot have an empty linked list; the length is always 1.
Would this be a proper way to implement a linked list in, say, a professional environment? Or perhaps there is a better way to do it? I am not a pr... |
Let me start by saying that the code works as is but I think it has a lot of redundancy. It is written this way as I kept getting nullpointerexceptions if I try to put the fileCounter > gameDiff if/else inside one for loop.
The program allows a user to create directories and add images to them. It will also display a c... |
I have been changing this code and I don't get to make it much better. I changed a little bit the structure, reimplemeted a new function for splitting Strings which is more efficient, etc. I have been tested with MR-Unit (it's part of map-reduce code).
I'm testing the code with 1.5 millions calls. It takes about 35 sec... |
I have created a small HomeScreen Widget which displays random numbers.
Attached is the code. Please let me know if the approach is good.
https://github.com/gottp/HomeWidgetTest
MainAppClass.java
package com.example.homewidgettest;
import java.util.HashMap;
import android.app.Application;
public class MainAppClass e... |
I'm new to C# and OO programing.
I have an aspx page with 3 lists of checkboxes and I would like to generate them from the DB.
how should I structure my code?
Here is an example of what I did so far:
ASPX page
<asp:CheckBoxList ID="CheckBoxList1" runat="server"></asp:CheckBoxList>
<asp:CheckBoxList ID="CheckBoxList2" ... |
I am learning getopt in Python to parse and validate command line inputs:
#!/usr/bin/python
'''\nMailing Script
Usage: python script.py -y <year> -c <type_user>"
Arguments:
-y, --year any value from 2008 to 2013
-c, --campaign any value in:
'80c', '80d', 'allowances', 'late_filing',
... |
In my project i work with COM object via System.Reflection. COM object returns pointer on structure VARIANT, that i cast as object and then i cast one as byte array. There are many structures that i get from COM object. Since i know about how organize these structure i write static class to deserialize them byte-by-byt... |
I am working on a (HTML/CSS) website to improve my skills but I am not sure if I am doing it the right way, because I have a lot of floats and sizes. I also need help with some CSS things:
What I have:
What I am Shooting for
The red dimensions in the image are the dimensions I've tried to give the objects and which I... |
I'm using this method from my Downloads() class in a back-end admin system, where these can upload some files, which must be .rar or .zip I'm not to concern about filesize, yet. Eventually, these compressed files, will be holding only .mp3 files.
Well, here's the code. As you can see, I'm checking mimetype against an a... |
I have created a list of files using find, foundlist.lst.
The find command is simply find . -type f -name "<search_pattern>" > foundlist.lst
I would now like to use this list to find copies of these files in other directories.
The 'twist' in my requirements is that I want to search only for the 'base' of the file name.... |
I am looking for some guidance and optimization pointers for my custom JavaScript function which counts the bytes in a string rather than just chars. The website uses UTF-8 and I am looking to maintain IE8 compatibility.
/**
* Count bytes in string
*
* Count and return the number of bytes in a given string
*
* @ac... |
I am having problem with a simple Hanoi tower program. I need to do something to reduce its time.
#include <stdio.h>
#include <fstream>
using namespace std;
int hanojus(int n, char a, char b, char c) {
ofstream fr("hanoj.out",ios::app);
if (n == 1)
fr<<a<< " -> " <<c<<endl;
else {
hanoj... |
Considering the code sample below, which approach of service method design would be considered best-practice and why? The one used in SaveOrder1 or the one in SaveOrder2?
UPDATE: To be clear, I'm not talking about web service here, but application-type-agnostic service class from my business logic layer. I marked parts... |
Here is my attempt at Weekend Challenge #3.
Out of scope:
It only will do 9*9
It will stop at the first solution
Could have been smarter at re-using the cache when recursively calling solveGrid
I ignored OO as this is not an app, but a simple script
In scope:
Bitflags & cache for pencil marks
var grid = "...84...9... |
Project contains 3 classes:
/*************************************************************************************
The purpose of this project is to create 3 classes. Pile contains the number of marbles
in a randomly generated pile, and also a remove method to determine how many marbles are
to be removed. The player cl... |
def current_time():
'''Returns a tuple containing (hour, minute) for current local time.'''
import time
local_time = time.localtime(time.time())
return (local_time.tm_hour, local_time.tm_min)
(hour,minute) = current_time()
def ishtime(hour, minute):
import random
Starting_str = ['it is','... |
See, I have a file which consists of a bunch of lines like
NAME:0001;some text
ANOTHERNAME:000103;some more text
NEWNAME:42; blah blah
So what I need to do is to have a list of those names, list of numbers (IDs actually, so the order matters) and list of further comments. I wrote a code, which actually does work, ... |
I need to display a list of category links, like so:
Category 1, Category 2, Category 3
I've got it working already but the code seems pretty repetitive and a bit of a mess, I was wondering if there was a better way of doing it.
This is what I've got so far:
for (var i = 0; i < data['categories'].length; i++) {
var... |
Is it possible to combine all the functions into a single function? I'm providing my fiddle as well.
I am trying to test it for different scenarios..
but I am not sure how to combine all the scenarios into one..
var myNumbersToSort = [null, -1, 2, 0.001, -3, 4, 0.3,1,-0.0001];
function getClosestToZero(set) {
if(0... |
There is a pattern that keeps coming up in my ruby code and I'm somewhat ambivalent about it. It's somewhere between a Hash and a Struct. Basically
I used method_missing to return/set values in the Hash unless I want to
override a specific value with some logic or flatten out the complex underlying structure in the JS... |
Project Euler Problem 10 asks: "What is the sum of all prime numbers below 2 million?"
How do I speed up my code? It's taking forever and I have never gotten the answer. However, I am sure that my code is right; I cheated the answer from online as I couldn't wait for an hour.
def isPrime(number):
for n in xrange (... |
I have created a generic repository for my MVC 3 page. I am using interfaces and a UnitOfWork. But before I set out to do this? Is this the right way to separate my databaseaccess from my viewmodels and views?
WHY I DID IT:
I want to seperate my databaseaccess from my viewmodels and my views, I also want the option to ... |
I have made this search filter and it works fine, but I think the code looks a little messy and I have no idea how to clean it up.
I hope the following makes sense, otherwise please tell me which information you need, and I will provide it ASAP.
// GET THE POST VALUE FROM FORM FIELDS
$field_value_service = $... |
I have a program written in PyQt that has a lot of content. The basic way I've been doing it is using a stacked widget with all the content on pages and buttons to navigate through the pages.
However, a lot of the pages are just the same stuff with maybe a couple of different things. What I've been doing is:
Initializ... |
I want my code to be reviewed and I'd like to hear your opinions.
Sun's code to compute hash of string:
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
r... |
The title could probably be better, but in any case here goes.
I am having a bit of a problem understanding how to move methods/functions to other classes to organize things.
So, I have moved a method of sorts, but as I am skeptical of it, I would like to get it reviewed and hear opinions on what can be improved.
Here ... |
I am using Dr.Racket, Intermediate Student with Lambda. I was wondering if there was any way I can simplify this code using any sort of method like lambda, abstraction, map, filter, etc.
; alien-at-edge?: alien --> boolean
(define (alien-at-edge? an-alien)
(or (alien-at-right-edge? an-alien)
(alien-at-left-edge? an-al... |
I am using Dr.Racket, Intermediate Student with Lambda. I was wondering if there was any way I can simplify this code using any sort of method like lambda, abstraction, map, filter, etc.
; DRAWING FUNCTIONS
; draw-rocket: rocket scene --> scene
; Purpose: To draw the given rocket in the given scene
(define (draw-r... |
Is there any other way to optimize the below code? I feel the below code is huge for the operations it performs.
{
if ((currentElement == null ||
(firstGridRow["Low"].ToString() == string.Empty ||
firstGridRow["High"].ToString() == string.Empty ||
firstGridRow["Mean"].ToString() == string.Em... |
I've created unit test for the "student" CRUD operations that looks like this:
[Test]
public void Can_Exec_CrudOps()
{
#region Prepare
var account = Processor.Execute(new CreateAccount
{
Email = "email@example.com",
Username = "username",
Password = ... |
This is more like a share and a request than a question. I converted Eric Lengyel's code, which calculates tangents of a mesh for the purpose of texturing and normal mapping, to support SIMD. For this I used DirectXMath library from windows SDK. I don't know if this is actually faster than regular floating point versio... |
I've played with F# for over a year, but I've only recently begun tentatively using it for professional work. I'm concerned that my c-style OOP principles are blinding me to the advantages of a functional language. I wrote the following code and it works just fine, but I feel like I'm just not quite using the language ... |
I have the following class designs, and I'm looking for the best practices, aligned to the OOP design principles/patterns.
The ParameterParser will be used inside a foreach block through 10 items approximately.
Any comments regarding the method body will also be appreciated, though the focus of the question is on the c... |
I recently started learning and programming Java based on a series of beginner videos created by a Youtuber (TheNewBoston), who had a tutorial on a calculator. So based on everything else I've previously learned, I have tried to mix it in to create a bit more advanced one. If you are able to minimize and clean up the ... |
I have a Django form with a lot of fields, including some FileFields. I want to validate the form based on the contents of the files: they must be valid gdal datasets, and if both are present (one of them is optional) then the optional dataset's extent must entirely cover the required file's extent.
To do this, I have ... |
I created a plug-in powered by jQuery that simplifies the developer's life to create responsive applications. It's flexible and I want to give to users a good syntax to write.
How can I improve this?
GitHub
; (function ($) {
var debug = {
ranges: [],
refreshRanges: function(ranges) {
thi... |
I'm working on my pet project with MVC 5 and EF, and everytime I'm adding a parent with it children (I have the children ID's) I have to go to the database, because if I just create a new child with this ID it just inserts a child object. Is there anyway to avoid this?
This is part of my code:
My classes:
public clas... |
I'm new to Java and have just started making JFrames. I wrote a program for a game project I'm working on and would like help on where I can improve. I'm not new to programming, I also know HTML and Python well.
I believe one of the goals for all programmers is to make a useful/fun program as simple and short as possib... |
The following code sorts an HTML table with JavaScript (without using any external libraries like jQuery). Are there any shortcomings or possible improvements I could make?
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=Windows-1252">
<script type="text/javascript">
var peop... |
I have created a MySQL query that works, but I feel there must be a better way. The query will be used by a PHP script whose purpose is to assign conditions & subconditions to new participants in an online experiment based on how many times each combination of condition & subcondition was already assigned to previous p... |
Below is my typical WindowController module for presenting a modal dialog (could be settings, asking username/password, etc) loaded from a XIB. It seems a bit too complex for something like this. Any ideas how this can be done better/with less code?
Never mind that it's asking for a password, it could be anything. What... |
Here is a implementation of the cryptographic hash function SHA1 written in Python. It does not use any external libraries, only built-in functions. I know that it would be faster to use an external library, but my code is for learning purposes.
I want to know if I am properly implementing the algorithm. Am I taking ... |
I am currently storing form data in an XML format:
<cfsavecontent variable="myFormData">
<cfoutput>
<ul class="xoxo">
<cfloop list="#form.fieldnames#" index="item">
<cfloop list="#form[item]#" index="eachItem">
<li><b>#xmlformat(item)#</b> <var>#xmlformat(eachItem)#</var>
</cfloop>
</cfloop>
</ul... |
I have used multiple lines of code in one if condition without using curly braces, which is executing properly. So what is the main necessity of using curly braces in if statements for multiple lines?
if (ggcCompareGrid.TopLevelTable != null)
foreach (GridRow row in ggcCompareGrid.TopLevelTable.Rows)
... |
I'm making a text-based RPG in JavaScript. It works but I'd like to know how to improve it, like code-wise. Also, I want to know how to make it run on anything other than Internet Explorer.
var canvas = document.createElement("canvas");
canvas.id = "canvas";
var ctx = canvas.getContext("2d");
canvas.widt... |
I've been working on a small "frame" for a text adventure in Python.
So it's less of a real adventure and more of a small testing location for all the commands.
I pretty much just started learning Python after completing the Codecademy tutorial and don't want to pick up any bad habits.
#Text Adventure
import shlex
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.