instruction stringlengths 71 95.1k |
|---|
For my CS2 project, I am supposed to implement a spell-checker. It is
supposed to follow the following:
Prompt the user for the name of the file containing the dictionary
of correctly spelled words
Read in the name of their dictionary file
Open an input file stream on their filename
If their filename successful... |
I have a strange programming prompt. I managed to complete an algorithm to solve smaller test entries (which i'll post). One of my test cases has to complete a 200,000 int input and my algorithm isn't practical. I'll post the prompt and my algorithm. How should I go about optimizing the performance to handle large inpu... |
I'm trying to develop a simple program to evaluate integral powers of a complex number \$z\$ , that is, \$z^n\$, where \$z\$ is in the algebrical form \$a+i b\$ and \$n \in \mathbb{Z} ^{*} _{+}\$.
How I was trying to proceed:
First, I defined a product function, and next I intended to define a exponentiation function ... |
I need to read HTML files and ignore the input until reaching the following tag <a class="member-modal" then print the characters between that and the closing <div> tag.
Below is the extracted line of the file of interest.
<a class="member-modal" href="https://website.net/users/membercard/890520">Phil Jankins<... |
This is probably silly, but I feel like there should be a much more elegant way to do this simple thing. I have two known strings, whichever one is passed in in the parameter I want to return the opposite. Current code:
def matching_sub(subscription_type)
if subscription_type == "maths"
"reading"
else
"math... |
I'm a beginner in MVC programming, repository, and UOW using Entity framework. I tried to calling my existing SP in my MVC project using UOW and EF.
Here is my code to mapping my SP in myDbContext file:
modelBuilder.Entity<Applicant>().MapToStoredProcedures(
s => s.Insert(
i => i.HasName("In... |
This program takes scores for each student from a .txt file and calculates their averages, as well as the average for each assignment and the class overall. This program works properly, just curious if I can make it look more professional.
Scores.txt
5
6
95.2 89.1 98.0 78.9 100 67
100 99.6 100 100 90.1 82.2
100 85.5 85... |
I realize this is very beginner code, but I just today grasped the basic concepts of private variables, constructors, and such. I wrote this very simple class, and a class to test it. Any and all input welcome.
Calculate.java
import java.lang.Math.*;
public class Calculate {
private final double num1, num2;
... |
I have a localization manager class which can change app language on the fly. It's using ReactiveCocoa and my main concern is that I'm not using some of RAC parts correctly.
First (in - (void)configureSignals):
+ (instancetype)sharedInstance
{
static i2KRLMLocalizationManagerObject *sharedInstance = nil;
stati... |
I know there are many great plugins on the Net nowadays. But due to safety issues, external plugin are restricted. Thus, I wrote some JavaScript for an interactively searchable HTML table. The main features I need are a vertically scrollable table and interactive filtering. Since the window size is not fixed, I also ad... |
The purpose of the code is to see if a form element would get data from internal react components and it did. It was also to see how clean I could make an autocomplete component.
The autocomplete has 4 states and I use bind excessively (is this bad?). I also added a function updateSpecificState, because I found it inco... |
I have a CLI wrapper for https://yakuake.kde.org/.
Python 3.4.*.
#! /usr/bin/env python
# coding: utf-8
import click
import subprocess
def get_postfix(title):
file_path = '/tmp/yakuake_{}_postfix'.format(title)
try:
with open(file_path, 'r') as f:
postfix_number = int(f.readline())
... |
Is this a good solution for the Number to Roman Numerals Kata in Javascript?
function toRomans(n) {
var nString = n.toString();
var result = "";
var allLetters = [["I", "V", "X"], ["X", "L", "C"], ["C", "D", "M"], ["M"]];
var letterSet = nString.length - 1;
for (var index in nString) {
resul... |
In order to solve a equation where the left hand side appears under an integral on the right hand side:
$$
B(p^2) = C\int_0^{p^2}f_1\left(B(q^2),q^2\right)\mathrm{d}q^2 + C\int_{p^2}^{\Lambda^2} f_2\left(B(q^2),q^2\right)\mathrm{d}q^2
$$
I have written the following code to do solve this equation iteratively:
import nu... |
We're given a char[] containing characters A-Z. (For more characters this can easily be extended). Now we're asked to remove all duplicates in the char[].
For example, in: \$['B','A','A']\$, out \$['B','A']\$.
The algorithm:
public void removeDuplicates(final char[] s) {
if (s == null || s.length < 2) {
return;
... |
I've been playing around with writing a simple static blog generator in Haskell (mostly for experience, since there's probably more than a few already made choices that fit my needs). I don't have very much experience with functional programming, but I've been doing a lot of C++ lately, so using typeclasses as "interfa... |
I have this code which is working fine but I would like to use Java 8 NIO in order to optimize the code performance.
public static HashMap<String, HashMap<String, Integer>> getTemp() throws IOException
{
HashMap<String, HashMap<String, Integer>> usageData = new HashMap<>();
File directory = new Fil... |
I would like a review of the following application, esp with how I'm registering and selecting the controllers.
First I defined a generic Repository interface and implementation using EF 6.1.2:
public interface IRepository
{
Task DeleteEntity(int id);
}
public interface IORepository<out TEntity> : IRepository
w... |
I'm working on an event manager, and I am wanting it to be a tool developers use. It is lightweight and it uses annotations to register events. I've tried to set up synchronization, and I'd like to ask if I'm doing it right so far. It's on GitHub.
The main class that I would worry about for synchronization would be the... |
Suppose we are given a C++ vector. We want to specify a variable amount of indices and select elements from a vector being indexed. I have two implementation: (A) one relies on C++11 initializer lists, and the second one (B) on va_list and macro mess. Arrangement B is however funkier to type because it requires no typ... |
I've been optimizing my code and I always tend to cache common selectors like this (jQ):
function init(){
var ob = $('#ob'),
fg = ob.find('.fg');
win = window,
s1 = $('#s1'),
s1em = s1.find('em'),
bodyHtml = $('body,html'),
fboxFirst = ob.find('.first'),
_continue = $('#cont... |
Here is an implementation of Graham Scan algorithm for computing the convex hull of a finite set of points:
data Point = Point {
xcoord :: Double,
ycoord :: Double
} deriving (Show)
data Direction = ToRight | Straight | ToLeft deriving (Show, Eq)
distance :: Point -> Point -> Double
distance a b = sqrt (((xcoord... |
I am trying to learn Socket.io and develop a multiplayer tic tac toe game. Right now, I have developed a game that plays well when hosted locally, but I cannot seem to transmit game moves between the client(s) and the server. How can I improve my game?
Index.html (with client-side JS)
<body>
<h1 id="title">Let's Play ... |
I am trying to get the scores and average for all assignments for records in a MYSQL database. The code below works but seems to take quite a bit of time to run because of the nested while loop. Any suggestions on how to combine the queries into one?
$query4 ="SELECT studentsisid,coursename,learningoutcomeid,learningou... |
I was recently rejected from what looked like a really promising string of interviews. I did very well in a questionnaire style review, and then they handed me this assignment (more or less):
Design a coffee machine which makes different beverages based on set ingredients. The initialization of the recipes for each dr... |
Based off of another SO reply by kennebec, I had problems following the code so I rewrote it to give myself a better understanding of what is being accomplished.
I would be very grateful if you could critique it or point out any problems I have caused or could modify to improve it.
Tested with IE8/9/10/11, FF, Chrome, ... |
The code included below was written in response to a programming exercise that was sent to me by a company that I am applying to. The purpose of the code is explained at this link.
This code passes 89% of all correctness tests for finding valid meeting locations as specified within the programming exercise information... |
This is my second program in Python. I am aware that globals are a bad idea, but that is what I have learned so far in my course.
Right now the program is doing what it's supposed to do, my only concern is that it might be too long for nothing. I'm asking you to help me figure out where I could make it simpler.
import ... |
A common task I often face is ordering a collection of items according to some predefined model, typically expressed as an ordered list of ranks. For example, credit agencies might rate financial products as:
AAA (excellent investment)
AA (very good investment)
B (not so good investment)
BB (poor investment)
BBB (why ... |
I'm working on simple a 16/24/32-bit bitmap reader for fun, however, the method I am using to go about reading the DIB header seems odd. All this does is read a simple Windows Compatible Bitmap from a file and stores it in memory.
The idea here was that I wanted to auto-populate members of a struct with the correspondi... |
I'm teaching myself data structures and would really appreciate some feedback on my stack implementation.
A couple of things I'm not sure if I should be doing:
creation of the array and pointer using new
style
// Implement 3 stacks with one array
#include <iostream>
class SingleArrayStacks{
private:
... |
I need to pass some int32_t values into and later retrieve them from a local storage API that uses void* and size_t parameters. Nothing else interprets the void* values.
I hand-made some simple functions to translate back and forth between the types, which work, but I wonder if anyone would care to let me know if they ... |
I ran the following code through Sonar, a static analysis tool.
Original file:
public interface LegRepository extends CustomRepository<Leg, Long> {
final String FIND_START_LEG_BY_TRANSPORTMISSION_ID = "SELECT ll.* "
+ "FROM T_Movement_Leg ll "
+ "INNER JOIN "
+ "(SELECT l.Transp... |
I wrote some extension methods to read CSV-styled text directly into a datatable or dataset or write them to this format. Is it right to use the methods as extensions or should I create a separate class that contains this functionality, and so on?
Formats explained:
The ReadFromCsv and WriteToCsv will work with a norma... |
I'm building a small MPL module in one of my utility libraries for fun and learning experience.
One of the problems I'm trying to solve is getting a list of all indices where a sequence of types appears inside another sequence of types.
Example:
static_assert(is_same
<
List<int, char, int, int, char, int, double, ... |
C code:
uint32_t pcg32_random_r(pcg32_random_t* rng)
{
uint64_t oldstate = rng->state;
rng->state = oldstate * 6364136223846793005ULL + rng->inc;
uint32_t xorshifted = ((oldstate >> 18u) ^ oldstate) >> 27u;
uint32_t rot = oldstate >> 59u;
return (xorshifted >> rot) | (xorshifted << ((-rot) & 31));
}
Attemp... |
I wrote a simple animation of a ball moving across the screen. I was wondering if I used the static variable correctly. If not, how could I make it non-static so I could instantiate it in the main method whilst being able to access its getter methods in the listener inner class? Also, did I use the SwingUtilities.invok... |
I was learning my way on designing real world OOP problems and I was trying to solve this problem in the OOP way. The problem statement is as follows:
The conference has multiple tracks each of which has a morning and afternoon session.
Each session contains multiple talks.
Morning sessions begin at 9am and must fini... |
After reading Designing a coffee machine yesterday, I decided I could also give the same problem a try.
I have used the following problem statement (copied from the given question):
Design a coffee machine which makes different beverages based on set ingredients. The initialization of the recipes for each drink should... |
I am building a small mobile app using ionic framework and angularJS. It will consume a Restful Web Service that requires authentication (User token). This means I need to keep my users token by myself. Could anyone tell me if there is room for improvement in my code? Specifically regarding to my "Session" service whic... |
A few days ago, I've made a code to equally distribute a set of numbers and retrieve them randomly. Today, I've rewritten the code (most of it, at least). I've followed most of the advice and tried to keep it clean, but also as fast as possible. The new code has a few more comments than the last one (they were needed) ... |
Given a set of values (points on a graph) find all the max/min points such that
there is no max is followed by a max (i.e. the max and min points alternate)
there is some minimum amount of change (C) between each max and min (.4 for this data set)
the value of the minimums must be lower than the adjacent maximums
He... |
What this command line utility does is to take a text file and update the content a bit before turning it into Markdown. For example, the first for loop searches all the straight quotes and replace them for curly quotes. The second loop searches for hr tags and replace them for * * *, then adds the noind class to the p... |
Further to my previous post for a user login script I've been learning PDO in order to migrate from mysql_* functions. As before with mysql_*, I wanted to wrap the PDO code into wrapper functions, so this is what I've done here.
I've created two functions:
db_connect(), which creates a connection and will be called at... |
I've written the following object pool class, and because this is my first encounter with synchronization primitives, I need reinsurance from an expert that this code is safe. I've tested it myself using 100 threads on a pool with a capacity of 4, and an expansion limit of 128, it appeared to be fully functional so far... |
I'm currently filtering a list based on several conditions, which may or may not be present:
def requests = Request
.list()
.findAll { if (exportFrom) { it.tsCreated.millis >= exportFrom.millis } else { it } }
.findAll { if (exportTo) { it.tsCreated.millis <= exportTo.millis } else { it } }... |
I have a library with two methods: one takes an object and vararg strings, the other takes a default value as well.
They are currently implemented as:
export default class koalaesce {
static get(base, ...steps) {
return koalaesce.getDefault(base, null, ...steps);
}
static getOrThrow(base, ...steps... |
I'm trying to improve my OOP skills in PHP. One of my projects requires me to get user info from one API and send it to another API with a different structure.
I will use a simplified situation, but basically I have a big user array from one API. I need to break this into sub objects (customer and address) and serializ... |
I wrote a simple calculator which uses orders of operations. I would like to know, do you see any serious flaws in logic and what do you think about this solution?
It is my second approach to a problem, and the code passes tests (with integers and decimals) for basic operations: ^,|(i used this sign for root square), *... |
My Goal: To efficiently move data from Amazon S3 to Amazon Redshift.
Basically, I am moving all CSV files on my S3 to Redshift using the below code. I parse through part of the file, build a table structure and then use the copy command to load data into redshift.
'''
Created on Feb 25, 2015
@author: Siddartha.Reddy
... |
I've written a function that works however I'm sure there is a better way. I need to parse specific tags from an xml document (Microsoft Word docx document.xml).
Here is the general structure of the xml in question.
//A ton of crap
...
<w:tbl>
<w:tr>
<w:tc>
<w:p>
<w:r>
<w:t>Data_I_want</w... |
I'm working in an application where there's a long unordered list of items that have to be paginated. New items are added to the list regularly, and the items come from a database.
The only control I have is via the front end. I cannot control how they are all loaded in the DOM before page load.
I was able to work this... |
I'm using JavaScript to handle breakpoints in a single page, non-scrollable application. I want to do various things when changing viewports, such as fire off animations with a JavaScript animation library.
I've assigned the viewports like so:
CodePen
HTML:
<div class='box'></div>
CSS:
.box {
width: 300px;
height:... |
Is this C appender safe, and reasonably optimal?
#define REALLOC_BUFFER_SIZE 4096
char *append(char *orig_str, size_t *orig_str_size, const char *append_str) {
// no action required if appending an empty string
if (append_str[0] == 0) {
return orig_str;
}
// does the current char* have enough ... |
I can't seem to get fieldset's to react properly when using display:table and display:table-cell even if I reset the default values, it just reacts oddly in a variety of ways in different browsers/devices, so as a result I have actually removed all fieldset's and replaced them with div's.
Is this a semantically accurat... |
I have opened a puzzle at Programming Puzzles and Code Golf. The question is not perceived well (yet) and one of the reasons is that no reference implementation is provided. To mitigate this shortcoming, I have implemented a (non-golfed and documented) reference solution.
I'd like your feedback about
Correctness acco... |
I wrote a class to represent a set of lights in a 2D game that raycast in order to find shadows. The draw method does a lot of calculations and takes a lot of time. Mainly, the adding of areas and clipping takes from 1 to 12 milliseconds per loop. Is there any way to speed up this method?
The whole project is on Github... |
This is my initial class. (I am not trying to reinvent state-flows again, just practicing)
As you can see straight forward, it dynamically generates methods like .recommend,.recommend!, .recommendation_sent?
class Project < ActiveRecord::Base
STATUS_TRANSITIONS =
{
initial: :not_started,
not_started: { val... |
How can I simplify this code?
<?php
class smth {
protected static $MARK_UNDEFINED = 'Undefined';
protected static $MARK_F = 'ECTS-F';
protected static $MARK_FX = 'ECTS-FX';
protected static $MARK_E = 'ECTS-E';
protected static $MARK_D = 'ECTS-D';
protected static $MARK_C = 'ECTS-C';
prot... |
The following function is basically asking the user to input a file name for a file that the calling program is going to do something with. If the user enters an invalid file name, I want the program to loop back and give them another chance. The code works, but is this the proper way to accomplish this? Also, are t... |
Some very common tasks that keep popping up from time time:
Find the most frequent something in a collection of things
... or the count of that thing
... or both (the item and its count)
Get the list of distinct items, with their counts, sorted by their counts
Get the N most frequent items, with their counts
To avoid... |
I have a timestamp (searchTimestamp) which I need to check to see whether it is less than 10 minutes old or not:
long currentTimestamp = System.currentTimeMillis();
long searchTimestamp = getTheTimestampFromURL();// this also gives me back timestamp in 13 digit (1425506040493)
long difference = Math.abs(currentTimest... |
I have been challenged by @nhgrif to write a Fraction class to better my understanding of OOP. I have found an interesting challenge here (I apologize that the source is not mentioned, I was not able to find it either).
Problem statement: Create a class named Fraction having two integer
data members named for a frac... |
I'm really new to PHP, and a little less so in WordPress. I've created a working function that spits out some static HTML into a page template in WordPress. I'd like to know if there is a best practice for this, perhaps someone can help.
function my_html_function() {
echo '<h4>Title</h4>
<ul class="ref-list... |
After doing a whole bunch of research on Onion Architecture, I have made an attempt at implementing this in a new system that we are developing.
We have the Layers as per below:
Domain
Domain.Entities
Domain.Interfaces
Infrastructure
Infrastructure.Data
Infrastructure.DependencyResolution
Infrastructure.Interfaces
... |
This is my RedisDataSource code. What I am mainly interested in is how the retry policy could be improved and if using WindowsAzure Trainsient Fault Handling this case (using Redis Azure Cache) makes sense.
using System;
using System.Threading.Tasks;
using AB.Common.Helpers;
using AB.SiteCaching.CacheCon... |
I was recently learning about nodes and how they work in lists, and to test myself, I decided to write my own LinkedList implementation in Java. Then I decided, that since there is already a LinkedList out there, why not make it sorted? So now it is a SortedList.
import java.util.Arrays;
import java.util.Collection;
im... |
Please check this PHP script. This script is for Login authentication
Some pre-defined constants to indicate the login state
define('LOGIN_NOERROR',0);
define('LOGIN_USER_CREDENTIALS',-1);
define('LOGIN_USER_EXISTS',-2);
define('LOGIN_USER_NONEXISTS',-3);
define('LOGIN_PASSWORD_LINKSENT',-4);
define('LOGIN_PASSWORD_BAD... |
Problem statement:
Create and maintain a Complete Binary Tree in C. Include the following
operations.
Insert a given key and perform inorder
Replace ALL occurrences of the given key with the then Last Element of the Tree. Then Remove the last node.
Query -> return number of occurrences of the key
Size -> Given a ke... |
Below is implementation 1 of data abstraction for rational number using functional paradigm written in Python:
#Use
def mulRational(x, y):
"""Violate abstraction by using other than constructor and selectors"""
return Rational(getNumer(x)*getNumer(y), getDenom(x)*getDenom(y)) #x and y are abstract data
def add... |
I need to reduce the latency in creating a circular gradient of arbitrary radius that's then mapped to the current mouse position.
Though the project uses OpenGL for video-card interaction, alas, for legacy reasons, currently uses aggdraw for drawing (with Pillow wrapping PIL). However, PySDL2 runs the rest of the UI,... |
In my team at work we have traditionally used VB, starting with 6 and moving to .NET. However, other teams in the company use C#. So, armed only with Programming C# 4.0 and VS 2013, I thought I'd have a go at it.
A relatively simple piece of functionality that I tend to use as a starter project to get used to a new lan... |
Based on this source, I've made the following universal get / set function, to make it possible to work on OrderedDict trees for example.
def nested_expand_and_get(d, keys):
intermediate = d
for key in keys:
intermediate = intermediate.setdefault(key, d.__class__())
return intermediate
def nested_... |
I'm learning Python and decided to rewrite my FTP tool from Perl to Python. The program is able to up/download files, change the directory and list the files of the current directory.
Is there anything I can improve?
#!/usr/bin/python
import time
import sys
import os
from ftplib import FTP
import getpass
def menue()... |
I'd like to know if I translated a piece of code correctly from C++ to Delphi. It looks like it is working, but I have a feeling that I'm reading and writing into memory that I'm not supposed to using Delphi.
Given C++ code:
struct tile_map
{
int32 CountX;
int32 CountY;
uint32 *Tiles;
};
inline uint32
Get... |
I am a beginner trying to fetch a random line from a file and wondering if this code can be improved. Should I use try and catch in this case? Should I take a parameter for the function "quote"? How can I take several alternatives for searchText? (E.g. "hello", "hi" or "hey" but one is enough to return true.)
def getI... |
I recently made a little program that shouldparse a logic formula (given in conjunctive normal form). I do the parsing with reloaded operator>> but I am not very satisfied with the workaround I used to get those operators recognized from a file different from the file they are implemented in.
When I need those operator... |
I want to visually inspect all the characters that Java thinks are in any given UnicodeBlock. The following method, as far as I can tell, does the task. But, it sure feels like awful design.
public static void displayUnicodeBlock(Character.UnicodeBlock block) {
int maxCharVal = (int) Math.pow(2, 16);
for(int cI... |
I would like to search a String, and for a certain word, I would like to change only the first 3 letters
For example:
This is a java institute which insures that you are in that institute. ins!
I want to change the first 3 letter of institute (ins) to JSE, so the result will be:
This is a java JSEtitute which insure... |
I decided to train myself in OOP with a simple perfect precision Fraction class.
from __future__ import division
import doctest
class Fraction:
"""
Implements a Fraction Class with perfect precision
operations and utility methods. The built-in operators
are overwritten to provide a more natural interf... |
I built a Tic-Tac-Toe game in Python. The board is made of ASCII characters and it is the user versus an AI. The user chooses a number (1-9) and if the corresponding spot is open then either an 'X' or an 'O' will be placed there. I wrote it in Python 2.7, then upgraded to Python 3.4, so I made it compatible with that. ... |
I'm learning about immutability and uniqueness in Java, particularly the use of defensive programming and object factories.
I have been asked to create a class containing an object factory that when called creates a unique registration number comprised of a single letter and 4 digits. I think my solution ticks all box... |
I'm kinda new at this jQuery stuff and I've gathered up this much to make my code functional, but I would really want to shorten it. I've already tried $('#Monday','#Tuesday'....) to group them, but with no success.
$('#Monday').click(function() {
if ($(this).hasClass("active")){
$(this).switchClass( "activ... |
I am a newbie trying to insert elements after the n:th element in the list. Any shorter/smarter ways?
def InsertElements(listName, var1, var2, n):
listName.insert(n, var1)
listName.insert(n+1, var2)
return listName
myList = ["banana", "orange", "apple", "cherry", "grape"]
result = InsertElements(myList, ... |
I needed a way to update a parameter in the URL, or add it if it doesn't exist, but keep any other variables the same value. I built this function to do the task, and while it works, I feel like it's taking longer than it should. Does anyone have any suggestion on what I could change or a faster method?
function chan... |
I'm in a little bit of a pickle on my Tic Tac Toe program because I can't see how to simplify the code without breaking it. Do I need to make my code modular?
public partial class dglassAssign4 : Form
{
string[] asImArr;
const int ciArrSize = 9;
int[] aiOrdArr;
int turn = 1;
... |
I am sorting an array (filtered) containing JS-Objects by their attribute sortdist:
filtered.sort(function (a, b) {
if (!a.sortdist) { return 1;}
else if (!b.sortdist) { return -1;}
else if (a.sortdist > b.sortdist) { return 1;}
else { return -1; }
});
However, I am sorting 9000 datasets, which takes a really ... |
Spurred by this question: Project Euler #8 I decided to try to solve it with as clean code as possible.
Here is the problem formulation:
The four adjacent digits in the 1000-digit number that have the
greatest product are 9 × 9 × 8 × 9 = 5832.
73167176531330624919225119674426574742355349194934
96983520312774506326... |
Is there a better way than this to copy the values from source to destination when the blocks of memory you want to copy to and from are different sizes? Also considering you have no control over making sure the sizes match to begin with.
while (count--) {
memcpy(dst, src, dst_stride);
src += src_stride;
dst +... |
This cache is like a list where new elements are inserted in the middle, cache hits are put to head of the list and replaced elements are taken from the end. Would I just use a list the lookup would take O(n). With a dictionary it is O(log(n)) but I lose the order of elements, so I use both.
.Net but only has Concurren... |
I have to read a int8_t from a buffer, read a uint8_t from the camera's current settings, add them together, keep new value within the bounds 0 to 100 and write the new value to the camera's current settings. This seems quite easy to me, and yet here I have a rather large bit of code.
The brace style is company-mandat... |
I have several classes for payment handling, I separate these classes into directories like below. Actually I'm going to use it for Laravel project but to make it simple, maybe we can talk as if it's native PHP code.
\Payment
PaymentServiceAdapterInterface.php -> an interface for service adapter
PaymentService... |
I'm making a matchmaking system using PHP and MySQL which allows users to search through a list of musicians so that they can find people with the right skills and interests who are near them. It works but it's extremely messy, and I'd like to learn how I can clean it up and eliminate as many bad habits as possible. I'... |
I follow this definition of "object":An object is a value exporting a procedural interface to data or behavior. Objects use procedural abstraction for information hiding, not type abstraction. Object and and their types are often recursive. Objects provide a simple and powerful form of data abstraction. They can be und... |
Below is the given exercise:
Exercise 5: Segments
Consider the problem of representing line segments in a plane. Each segment is represented as a pair of points: a starting point and an ending point. Define a constructor make-segment and selectors start-segment and end-segment that define the representation of segment... |
I have a function that returns some preferences, but first I have to do some checks to see whether the user is authorised to read them. I'm still not happy with the result (the match is a bit ugly).
Note: Result is a framework class, it just means some kind of response.
// implementations are not relevant.
def canAcces... |
Sample files:
./data/foo/file1.xml
./data/foo/bar/file2.xml
./data/baz/file3.xml
Corresponding output:
./out/foo/file1.xml.xml2
./out/foo/bar/file2.xml.xml2
./out/baz/file3.xml.xml2
The subproblems are:
Find all xml files in data/
Construct the output path: replace data/ with out/ and add an additional extension
Cr... |
Please have a look into this problem:
Little Dipu is a small kid and like all the other kids, he likes to
play, but he plays with numbers (he is extraordinary you know).
Nowadays Dipu has some extra interest in odd numbers. So, he says that
a number N is interesting if it has odd number of divisors. Now Dipu
t... |
I have a sort function that needed to sort in a certain way. That position was sorted by mobile-top first, then empty position followed by mobile-bottom. Then on these I needed to sort by their priority, with priority 1, 2 and then blank.
widgetInfo = [
['box1','mobile-bottom',''],
['box2','mobile-top','priority-1'],... |
I think there must be a more pythonic way to achieve the lowercase-forcing that I need to do here. The keys in my lookup (self.adjustments) are all lc, params sent in to function can be any case (data coming from third party). Also, is it objectionable to have self.adjustments used here but not passed in?
def getReve... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.