instruction stringlengths 71 71.9k |
|---|
I have created a nice url structure for my site.
In my .htaccess I have:
FallBackResource /index.php
And in my router class I have:
class init {
function __construct($url)
{
$URLElements = explode('/', $url) ; // Adjust if needed.
if($url)
{
$class = $URLElements[0] ;
if(substr_count($ur... |
See Randomizing and mutating algo class - style
I'm looking for a review of the functionality of this code, answers to the above question which also describes the code use focus on style instead.
Below is the updated code since the style feedback.
algo is an algorithm that is dynamic. algo instances can be created, ask... |
Despite being the clever Java coder I am, I noticed I know way too little about various design patterns. The builder pattern caught my eye as something to learn, as I have certainly seen my fair share of telescopic constructors already.
So, I decided to give it a try. The following is a really simple class represents a... |
This question is related to this thread
StackOverflow
I would like to share with you my code, that is supposed to read a bibtex file and perform some analysis on it.
The code works fine, but I'm uncomfortable with the chosen data structure (list of dictionaries).
By posting the code here I hope to get feedback from thi... |
I made a mobile store, with prices in Indian rupees. Now I went for nested switch over functions, because I wanted to try out something new - biggest mistake in my life.
Since 3 days I've been trying to perfect it, it just won't happen. I have to make sure the menu shows again if negative number or a character is enter... |
i am trying to implement factory pattern for getting XML Document from server
(using javax.xml.parsers.DocumentBuilder)
I have the classes below for now, could you give your opinion ? Does the structure make sense for this pattern?
DocumentGeneratorFactory (abstract factory)
public interface DocumentGeneratorFactory... |
My apology, I am quite new to posting a question in this forum.
I had a task where I was supposed to write a solution to sort entries(Name, score - in an array/list) in order of score and generate ranking based on higher score to lower scores.
I tried doing that, code is working what it was supposed to do but it seems ... |
var WorkflowDialogBuilder = _.once(function () {
'use strict';
var workflowDialog = $('#WorkflowDialog');
var workflowDialogContent = $('#WorkflowDialogContent');
var events = {
onApplyChangesSuccess: 'onApplyChangesSuccess',
onValidationFailed: 'onValidationFailed',
onDialogOp... |
I would dearly love some feedback on the model below. It's a basic commenting structure where users can comment on a variety of objects in the model. I have denormalised it to make querying simpler, but I'm not sure if I've over/under done it. The model tests fine, but it all feels a little clunky.
#################... |
By reading some tutorial i have written some peace of code to do crud operation . I just want to know how is this code is efficient or how can i make better ?
Here i am giving code of 3 class
1. EntityManagerProvider : get connection from DB and do crud operation
2. BaseDao : A generalised Dao which uses EntityMana... |
Forward
I would love any comments you have, any ideas, any flaws you can find, and any suggestions you might have regarding the code below.
If this is similar to other implementations, I would love to know about them, since this is something I came up with by myself, after not finding any solution 'out there', but I kn... |
I had a task where I was supposed to write a solution to sort entries(Name, score - in an array/list) in order of score and generate ranking based on higher score to lower scores.
I tried doing that, code is working what it was supposed to do but it seems very ambiguous and tightly coupled, I can't even write a unit te... |
I was trying to solve the Next Palindrome problem listed in SPOJ in Ruby language. Please find the problem statement here. Though i came up with the below solution, i could not get the execution time below 1.4s even after tweaking this code numerous times. Where can this code be optimized in terms of memory and executi... |
Consider the following simple relationship.
Code
[DataContract(Name = "Wheel")]
public class Wheel { }
[DataContract(Name = "OffRoadWheel")]
public class OffRoadWheel : Wheel { }
[DataContract(Name = "RoadVehicle")]
public class RoadVehicle
{
public Collection<Wheel> Wheels { get; private set; }
public Road... |
I have the below code which is still under development - but I'm trying to get myself to find the ideal way to move forward.
public interface IMemberSubscriptionService
{
void SelectSubscription(IMember member, IMemberSubscriptionTypePrice subscription, IOrder linkedOrderPaidWith);
IMemberSubscriptionRenewal Ge... |
Heres the link to the original question . Billboards Link
I initially declared n*k array which led to a Out Of Memory Exception.
Then I resorted to using just 2 * k matrix and alternating between 0 and 1 during each iteration. Now the issue is time limit. As of now 8/10 cases are solved using this approach.
using Sys... |
Obviously there are better ways of obtaining Pi, but for educational purposes, how is the code below?
(defn leibniz-numerator [x] (* (- (rem x 4) 2) -4.0))
(defn calc-pi-leibniz
"Calculate pi with Leibniz formula
4/1 - 4/3 + 4/5 - 4/7 + 4/9 etc
Very slow convergence"
[terms]
(reduce + (map #(/ (lei... |
I retrieved 200 tweets using the Jersey API. I want to find two tweets which have the longest common substring.
tweetList is an ArrayList of Tweet objects. The comapreTweets method compares tweet objects for longest substring.
Tweet t1=new Tweet();Tweet t2=new Tweet();
int longestString=0;
for(int i=0;i<tweetList.size... |
Here's my first effort at reformation: a business letter I wrote for a friend. I would appreciate a review. (Yes, I know this is a trivial example and it would be much more beneficial to have something reviewed that is more complicated. But I want to nip bad practices in the bud now, before they become embedded in m... |
I created jQuery code to automatically insert new input field when the previous field is focused. The code works well but seems rather lengthy to me.
What I'm currently doing is cloning an element and then modifying the clone's attributes. As I add new a element into a DOM, I also need to modify this element and increa... |
Here is the code I am using to apply DCT on 8x8 blocks, which I'm not sure is correct. I have tried to follow Wikipedia's discrete cosine transformation (DCT) formula as closely as possible. Please let me know if there are any changes to be made.
//round up a float type and show two decimal places
double rndup(double n... |
I often have static classes which uses the DataContext somehow, and they all make a new DataContext, but often I already have one instantiated elsewhere, so why not use that?
public static bool SignIn(string email, string password, DataContext db = null)
{
bool disposeDb = false;
if (db == null)
{
... |
I want to direct all requests that haven't got a valid controller action to my custom page controller.
I.e. I want /pages/new & /users/login etc to work correctly, but a request for /foo or /foo/bar should be directed to /pages/display/$path.
The following code works, but I'm pretty certain I'm not doing something th... |
I'm starting with OOP for php, i get the idea, but don't have someone physical near me to fallback on so I'm hoping i can do that here.
The following works but i would like to know if it's good practice, that is something that weights a lot for me.
Concept is that you can create an object, the data for this object is g... |
This is my work to generate an infinite Shepard Tone. It is written in Clojure and works by generating repeating streams of incrementing frequencies, converting those to values on a sine wave and then adjusting the amplitude to fade in and fade our the audio.
Multiple concurrent streams gives the illusion of an ever in... |
I have written a small JavaScript class that makes use of setInterval to create a delayed loop for iterating an array. I've used this technique in the past but never utilised a library to do so (and as a result it produced quite messy spaghetti code), and so I wrote up this:
var DelayedLoop = function() { };
DelayedLo... |
This is function, that works correctly, but it seems to be too ugly.
panel argument is never used for anything but pushing into refreshGamePanel,
and it seems to be too much case statements. How can I cleanup this?
runGameLoop :: Game -> Panel -> Curses GameResult
runGameLoop game panel
= if victory game then return ... |
As per suggestion on SO, I am posting my code here to be reviewed. It was said I should not be saving and reading from disk so many times when a user selects and deselects a cell in my tableView.
@property (nonatomic, strong) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSArray *list;
- (void)viewDi... |
According to this two questions: [1] and [2]
I need a way to combine these two methods of handling the event attachment in jQuery.
$('selector').on({
mouseenter: function() {},
mouseleave: function() {},
mousedown: function() {},
mouseup: function() {}
});
I prefer the previous method but need some... |
As the question reads, I am building a database with 3 tables. Now these tables are going to be used to store names.
Table 1 will store First Names
Table 2 will store Last Names
Table 3 will be a one to one table linking the First names to the Last names
Now all this data will be coming from a text file in the form... |
I was searching for a free implementation of a "bounded" priority queue. The algorithm has been discussed many times on Stack Overflow. I took a shot and wrote a STL-like bounded_priority_queue class (which implements the most efficient algorithm using a priority_queue with a "flipped" compare as the underlying conta... |
I'm working on a site that has to do with movies. I am consuming the Rotten Tomatoes API to get my movie information and using EF5 with a code first approach to get that into the database. I'm using MVC4. I am struggling to come up with a design that makes sense and accomplishes what I need to in an efficient manner wh... |
I would like to improve my preg_replace regex.
This is to clean a features list.
I want allow for the begining of each line:
alphanumeric characters
== and alphanumeric characters
-- alphanumeric characters
++ alphanumeric characters
** alphanumeric characters
my regex:
$features = "
== Category one
→ feature... |
How can this be written a bit shorter?
jQuery.konami = function(fn, code) {
// ↑ ↑ ↓ ↓ ← → ← → B A
code = code || [38, 38, 40, 40, 37, 39, 37, 39, 66, 65];
var kkeys = '',
i = 0;
$(document).keydown(function(e) {
var char = String.fromCharCode(e.which).toLowerCase();
if (char =... |
Based on the answer to my question on StackOverflow, I have ended up with the following code:
public class ColumnDataBuilder<T>
{
public abstract class MyListViewColumnData
{
public string Name { get; protected set; }
public int Width { get; protected set; }
public ColumnType Type { get;... |
I wanted to get the boolean status from a function. Here is my sample code, wherein I used return in try and catch, to get the status of function.
public static void main(String[] args) {
System.out.println(getState() ? "successful" : "failed");
}
public static boolean getState() {
SAXBuilder builder =... |
I need to divide an array in blocks of 6 items max, however I can't find a better way to store the last block.
This is my current code and it works. Is there a way to avoid using the if after the .each ?
var tabsData = [], tabCtr = 1, lpcCtr = 1;
$.each(PAGE_DATA.tableData, function(i, item) {
tabsData... |
I have this code to create an inverted index from a directory of text files:
(def p (re-pattern #"[^\p{L}&&[^\p{M}]]"))
(defn invert[file]
(let [f (.getName file)
tokens (.split p (lower-case (slurp file)))]
(into {} (mapcat #(hash-map % #{f}) tokens))))
(defn build-index[dirname]
(reduce #(merge-... |
I'm in the midst of writing a custom ListView for our application.
In the process of getting this question answered, I realized I needed to separate my column-generation logic from the data population. This led to the need to preserve the ColumnDataBuilder<TDATA> builder object that I used to create the columns, so ... |
I have a small validation code that needs to make sure that exactly one of two parameter is
set
I consider two options, the "Naive" that has some repetitions and might look "clumsy" but is very clear, and a second that is a bit more "DRY" but I'm not sure it's as readable / convincing in it's correctness.
Option one
i... |
I'm currently clearing my console window with this piece of code:
void clrScr()
{
COORD cMap =
{
0, 3
};
if(!FillConsoleOutputAttribute(hCon, 0, 2030, cMap, &count))
{
std::cout << "Error clearing the console screen." << std::endl;
std::cout << "Error code: " << GetLastError(... |
Everyone knows you can't put a Derived in an std::vector<Base>. I decided to implement a collection which does allow you to do this:
#pragma once
#include <boost/iterator/indirect_iterator.hpp>
#include <type_traits>
#include <vector>
template<typename T, std::size_t BLOCK_SIZE, std::size_t ALIGNMENT=alignof(T)>
clas... |
I have verified that both of my following functions successfully find prime numbers. I was pretty sure the function called is_prime_new would be faster than is_prime_old; however, after benchmarking (mainly consisting of generating huge lists of primes), I found this to be significantly false and I'm wondering why this... |
I am wondering am I doing the right "Drupal" way in getting formatted value of node's body field. Here is my code:
$field = field_get_items('node', $node, 'body');
$body = '';
if (isset($field[0]['value'])) {
$body = check_markup($field[0]['value'], $field[0]['format']);
}
|
I have the following in the header.php file which is included in all of my views:
$dh = opendir(Vs.get_class($this).'/js') ;
while($script = readdir($dh)) {
if(!is_dir($script))
{
echo '<script type="text/javascript" src="js/'.$script.'"></script>' ;
}
}
$dh = opendir(Vs.get_class($this).'/css') ;
... |
I have an IWorkflow interface defined as follows:
public interface IWorkflow
{
Task ConfigureAsync();
Task StartAsync();
Task StopAsync();
}
And I have an Engine class:
public sealed class Engine : IEngine
{
private readonly List<IWorkflow> workflows = new List<IWorkflow>();
public Engine(IEnumera... |
I have written this program after a lot of effort, and I was wondering about the efficiency of that solution and if it's neat.
How plain is this program and is there any better way to rewrite it?
import string
# Strength of operations:
# -> [] (brackets)
# 6 -> ~ (negative)
# 5 -> @, $, & (average, maximum, minimum)... |
I created a function to calculate the font size to fit the width of the website I'm doing. I believe the code is a bit ugly and could use some improvement by creating a more logical function, faster and less heavy.
Can someone look at the code and comment on it for my own improvement?
//Script jquery
$(window).resize(... |
Below is my current code for sorting an array, "$jobs_list".
It's not very DRY and it's fugly. And there are several more similar case statements still to go in. How could I write it so my brain doesn't twitch to look at it?
switch ($sort) {
case 'number':
usort($jobs_list, function($a, $b){
ret... |
I've built a Connection class that uses a PDO connection, but it looks messy and im sure there are ways of improving it. Currently I only want 1 instance of the connection (singleton).
<?php
namespace AQEConnect {
use \PDO as PDO;
/** Includes */
require_once dirname(__DIR__) . '/config.php'; // Contains ... |
I have been presented with a simple but slow performing LINQ to Entities query which I've pasted below.
Could anybody give me some pointers on how to improve performance? The query below has been significantly improved since I inherited it but I don't know what else I can do without moving to the DB (which isn't an op... |
Mask.html
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="mask.js"></script>
<link rel="stylesheet" type="text/css" href="mask.css">
</head>
<body>
<div id="div1" style="margin: 5px; b... |
I've written a die roller which can be run from the command line. It currently exists as three files, but I'll say later why I'd like to make it four. The files are as follows:
die.py: Defines the Side and Die classes and extends Die with the NSided and Fudge classes.
summer.py: Defines the default Summer class and ... |
@implementation User
- (void)refreshProperties
{
assert(!self.isSyncing);
NetworkOperation *op = [[NetworkOperation alloc] initWithEndPoint:GetUserDetails parameters:nil];
[self setupCompletionForRefresh:op];
[self setNetworkOperation:op];
[self setSyncing:YES];
[[NetworkManager sharedManage... |
I've created a class that's used for cleaning variables for use. You set a name, value and options and it will set the value if it matches the criteria/options.
It is used like this:
$var = new Variable();
$var->clean('username', $_POST['username'], '3,13,alphanumeric,True');
echo 'Username', $var->clean("username");
e... |
I tried to write a nullptr_t class based on the official proposal to be used in C++03 only. The only differences with the proposal are that we can compare two nullptr_t instances and that it is convertible to bool via an overload to void* to avoid unwanted behaviour such as int a = nullptr; for example. Here is the cla... |
I have finished my router and would like your thoughts on anything that may be inefficient of could be done better!:
class Router {
public $start_page = 'Dashboard' ; // Change to your home/default page.
public $staticRoutes = array(
'alias' => 'ActualController',
) ;
function __construct()
{
$url = substr(rt... |
This is one of a classes (that sends email based on object type to AM (role)) that is executed by an engine. I also have commands like SendEmailToAOCommand that send email to a role AO based on object type and so one.
namespace SFE.Workflow.Commands
{
public class SendEmailToAMCommand : ActionCommand
{
... |
I am having trouble designing a module, can anybody help me?
Because it will be hard to maintain this kind of module, I also think that this can test my skill of design pattern usage.
Requirement
This is basically an agricultural project (web application). I need to design a module where some calculation takes place.
T... |
I would like to know if there is a more efficiency way to speed up below code. It uses a procedure where subsampling is required in the nested loop (which a previous answer helped to make more efficient).
R has a tendency to hang when B=500, although computer OS isn't unduly affected. The goal is to run the below code... |
I have been reading some NumPy guides but can't seem to figure it out. My TA told me I should be able to speed up my code by using a NumPy array instead of a for loop in the following segment of code.
for neighbor in get_neighbors(estimates,i,j):
pXgivenX_ *= edge_model(True,neighbor)*observation_model(obs,... |
I'd like some tips on optimizing the following code.
I'm a bit concerned that I'm 'polluting the global namespace' by not wrapping it in a function. The commented out var rotator { init { came from a JavaScript tutorial but I'm not sure it's the jQuery way? Should I wrap it in $(function()... instead?
$(document).ready... |
This nests Google Maps Event Listener for click or drag. How should I refactor the last part where it reuses the function getAddressComponents()? If there are other parts to be refactored, please do offer suggestions.
function getAddressComponents() {
geocoder.geocode({'latLng': marker.getPosition()}, function(re... |
I've just made this class, which supports caching. I'd really appreciate any comments on how to make it better etc.
Code
<?php
/*
*
* PHP Validation Class
*
* The currency rates are fetched and cached for the whole day
*
* http://prash.me
* http://github.com/prashles
*
* Uses http://rate-exchange.appspot.com/currency... |
I have a class that uses the SqlBulkCopy to bulk insert data into a SQL Server database. My original implementation just passed the m_buffer (which is a reference to a class that implements IDataReader) directly into the WriteToServer. Now a new requirement has been added that, upon failure, the process should retry t... |
I have made a small project and I am just wondering if I could add more functionality to the project e.g more classed etc. Is a better way of displaying my results and what error handling I could do?
I was also wondering what would be the best way to add Inheritance to the this project.I was thinking a EveningCourse c... |
I'm trying to come up with a way to make a drop down box that is displayed through a jquery mouse hover event and with nested dropdown boxes displayed through hovering over elements of the original drop down box. I wrote some terribly inefficient code and I'm struggling to find ways of simplifying it. If anyone has any... |
How I can rewrite or refactor my controller code? I have the same SQL query (@plan_gp_users) in all defs.
class PlanGpsController < ApplicationController
def index
@search = PlanGp.joins(:user).search(params[:q])
@plan_gps = @search.result.order("created_at DESC").page(params[:page]).per(15)
... |
One thing I realized while going through code yesterday at my internship is that I run sql queries quite often. So I decided to write a function to keep all of the calls in one place and reduce the number of lines of code. It doesn't cover all possible sql calls but it does cover the basic calls I believe.
So my quest... |
This code basically changes the color of the lines and move text for menu navigation. Is there a simpler way of writing it?
$('.nav1 a').click(function () {
$('.nav1').addClass("current_nav1");
$('.sf_menu li').removeClass('current_nav2 current_nav3 current_nav4 current_nav5 current_nav6');
$('#content, #h... |
I created a simple wordfeud solver that checks what words can be created with the supplied letters.
public void GetResults(string characters)
{
// place all the characters we have in a dictionary with key=letter, value=amount
var charCount = SplitCharacters(characters);
// get all the unique letters (the k... |
Is the following PHP laid out fine to go inside the mail function?
$to = "My Name <myemail@mydomain.com>";
$subject = "Contact Form: $name";
$message = "Name: $name\r\nEmail: $email\r\nMessage:\r\n$message";
$headers = "From: Contact Form <contactform@mydomain.com>";
mail($to, $subject, $message, $headers);
Should t... |
The zlib library is a venerable piece of C software. The copyright for the decompression routine goes back to 1995, with the last rewrite in 2002. It is used daily by millions.
To be perfect, the decompression routine should not invoke undefined behavior, even if passed a maliciously crafted buffer. I have the opportun... |
I have two different ideas on how to handle this Update method in my MVC Model class "DataAccess" And I'm wondering if in the first, I'm handling my class incorrectly or ambiguously, because I'm using members from the same object for two different purposes.
The man Class has 2 relevant members. ID, which is the primar... |
I load in static setting via an ini file. Ini file have the benefits
of NOT being server by most web servers by default.
easier to edit than XML
even simplier than JSON
Setting get loaded in Application.cfc
void function setupApplication() output="false" {
...
application.stAdminSetting = application.loadini("admi... |
I am a new developer therefore I have many questions:
In this class I get file path on the disk (wireshark file that needs to be converted to pcap format extension) and convert it with the method convertFileToPcap(), in the constructor I am calling convertFileToPcap() and from the main after create the Editcap object I... |
I was being troubled a lot by Robocopy (or maybe anti-virus or maybe Network Hardware). I copy files from the Dynamic View of Clearcase to the local machine for a fresh build. The copy would frequently fail due to:
2012/12/06 15:35:07 ERROR 64 (0x00000040)...
The specified network name is no longer available.
The se... |
def dec_to_bin(ip):
ip_array = ip.split(".")
ip_array = filter(None, ip_array)
if len(ip_array) != 4:
return "Invalid IP Address format"
else:
ip_bin = []
for x in range(len(ip_array)):
# Formatting example referenced from:
# http://stackoverflow.com... |
This class acts like a synchronization context except the work could be done on any one of the available threads.
I've done quite a bit testing on my own, but I'm generally concerned about potential deadlocks. (I'm also curious if there are better ways to accomplish my goal.)
I created it because I have a 3rd party lib... |
I have created an api in php and I was hoping some clever individuals would mind reviewing it to see what I could do better. I have commented it heavily to explain my reasoning. please feel free to pick holes wherever you can!
//On my page 'localhost/api'
if (!$_POST) {
die('No direct access allowed');... |
Please help me to make more readable and simple code like this. What if I had 20 components? Is it right to organize code like this?
package newpackage.view;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swi... |
How would you refactor this kind of code? I've unsuccessfully tried several approaches (NSArray, NSPointerArray, plain C array), but always ran into pointer type checking error.
NSError *error1;
NSError *error2;
NSError *error3;
//imagine MANY of them
[object1 methodWithError: &error1];
[object2 methodWithError: &error... |
Here is my new STL-like implementation of an unweighted graph. Could you please tell me what member functions I should include in my library?
unweighted_graph.hpp
#include <algorithm>
#include <stdexcept>
#include <vector>
#include <map>
#include <set>
using namespace std;
#ifndef __UNWEIGHTED_GRAPH_HPP
#define __UNW... |
I have made a student details project. The user is asked to enter the info for two students, which is then displayed on the screen.
Questions:
Have I used inheritance correctly?
What would be a better way of outputting the results?
public class Person extends Test
{
// Variables
String name... |
Here is Python code written to perform the following operations:
Find each occurrence of a three-letter sequence in a character array (e.g. a sequence such as ('a','b','c')), including overlapping sequences of up to 2 shared characters.
Count the characters between the start of each sequence and the start of all ident... |
I'm writing a custom dictionary which is to be used as a helper for caching. The reason I use delegates is because it must interface with generated code, so I can't change this. However, you can assume that the delegates are thread-safe. I did some preliminary tests that it's thread-safe, but I can always use an extra ... |
Imagine a website that publishes the number of daily commuters in only a graphical form each day using a bar chart. I want to determine the number by reading the bar chart after saving the graphic as an image (the image stuff is not important here). The way I want to read the bar chart is by going to a pixel number (... |
I wanted to open Database (Mongo) connection only once when I start application and share the same connection across the application. What am doing as part of app.js is
Creating connection
var dbConnection = mongoose.createConnection(config.database.address, config.database.dbName, config.database.port);
passing dbCo... |
I'm new to jQuery and played a bit with what can I do with radio button. I want to create ONLY one input type when I click the Notice radio button. I already using many way to achieve this, but this is the only way I can do this, you can see the following code.
HTML
<input type="radio" name="radio1" value="Immediate" /... |
I want to store image (details) in my database, and want for each image the possibility to have from 1 to N versions.
I want a single file (src) to be associated with a single version. There must not be more than one version for an single image with the same dimensions and format (no point having a version with 1920x10... |
I will try to be as concise as I can:
The goal: trying to universalize a specific section of a project, that is dealing with the SQL database transactions.
To assist you with your answer, I've pasted the following (just for reference):
a usage code: GetTestOfTablTime() returns a DataTable
class: SQLDBInteraction is a... |
I want to use this function to store 1024 bit keys in my Mysql database. If you call generateKey(128), you'll get a 128 byte string, same as 1024 bit string. I want to know if there is something wrong with this code or if I should be worried about inter-operability issues with MySQL, Java, Android, File Read/Write, etc... |
I've just written a validation routine for a UPC-A, which ensures the check digit matches the given UPC number (according to rules I found on Wikipedia).
Below is the code, what do you think?
function valid_upc_a($value)
{
$odd_sum = $even_sum = 0;
if(strlen($value) != 12) return FALSE;
$chars = str_split($... |
I am building a time tracking application and my requirement says that any hours past 40 total should be counted as overtime and not regular hours.
Which function is more clear? What can be done to clarify the function? Even the second one at ~ 10 lines seems wordy
Option #1
function calculateOvertime(days) {
var t... |
I wrote a function in Scala to find out and return a loopy path in a directed graph.
One of the arguments is a graph presented in an adjacent list, and the other is a start node. It returns a pair including a loopy path by a list of nodes.
I wonder if there are more elegant ways of doing this.
def GetACycle(start: St... |
I'm trying to come up with the most basic example of making a JQuery slide show where you click on the current image you're viewing and you cycle through a gallery of photos. I know its probably not the most basic example, because if I want to add a new image I have to code more JQuery. Is there a more abstract approac... |
I've written an extension method to truncate strings:
/// <summary>
/// Returns the string, or a substring of the string with a length of <paramref name="maxLength"/> if the string is longer than maxLength.
/// </summary>
/// <param name="maxLength">The maximum length of the string to return.</param>
/// <exception cr... |
I have to implement a tree programming here. What I mean by tree programming is I have data stored in tree format. I have a parent object which will have child objects of same type the level of depth can go any long:
I am able to store objects in tree format and also able to display properly. I am facing problems wh... |
This is a working example that I am trying to improve.
Throughout the application I am working on one of the requirements was to have tooltips everywhere. However the customer wanted the ability to see a "Summary" of these tooltips and be able to manage them from a single location.
What I ended up doing is creating a... |
As a learning exercise, I'm developing my own PHP framework. I'm looking for a way to "load views" (kinda like CodeIgniter does it), without polluting my general scope.
I came up with the following, basic, example:
$data['test'] = 'Hello world';
$str = load_view($data, true);
echo $str;
function load_view($dat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.