instruction stringlengths 71 71.9k |
|---|
Description of the Readers–writers problem.
It looks like it works, but I have some doubts:
class ReadWriteBuffer<T> {
private static final Object writeLock = new Object();
private static final Object readWriteLock = new Object();
private int numberReaders = 0;
private int numberWriters = 0;
pr... |
To improve my programming style, I have been writing solutions for popular code katas. I have written a partial solution for the Berlin Clock kata and have been trying to follow the SOLID Principles. Can anyone critique the code and suggest improvements?
public class BerlinClock {
private static List<TimeUnit> tim... |
E.g: if a linked list contains 2->3->1->3->4 then the result should be 2->3->1->4. Notice that 3 has been eliminated.
This code is attributed to GeeksforGeeks. I'm looking for code-review, optimizations and best practices.
public class EliminateDuplicateUnsortedLL<T> {
private Node<T> first;
private Node<T>... |
I'm trying to make a simple console application game. The code is a bit messy and I hope anyone can point out anything wrong.
using System;
using System.Collections.Generic;
namespace CalculatePoints
{
class Program
{
static void Main(string[] args)
{
Game game = new Game();
game.PlayGame();
... |
I might not be keeping with Single Responsibility with my DAO. I also implement a custom observable through update. It makes sense because when something changes in the data, then it makes sense for the observers to be updated. Is there way for me separate them but still able to update when I update the data structur... |
The following code, written in synchronous Node.js and intended to be used as a shell script, nests a try/catch inside a conditional.
Because both the conditional and the try/catch serve a similar purpose - respectively, check a file exists, and check that reading and writing to it succeeds - it feels clumsy that the c... |
A group of basic sorting algos. Based on Algorithms, 4th Edition - Robert Sedgewick | Kevine Wayne. Just making sure all of my logic and everything is correct.
/*
Sandbox for the various search algorithms from Section 2 of
<a href="http://algs4.cs.princeton.edu/home/">Algorithms, 4th Edition - Robert Sedgewick | ... |
I have this tooltip code that I came up with, using jQuery:
$('div.a')
.bind('mousemove', function(e){
$('#follow').css({
left: e.pageX + 20,
top: e.pageY
});
})
.mouseenter(function() {
$('#follow').css('display','block');
})
.mouseleave(function() {
$('#follow').css('display','none');... |
This is my code in C# for performing insertion sort:
static int[] performInsertionSort(int[] inputarray)
{
for (int i = 0; i < inputarray.Length-1; i++)
{
int j = i+1;
while (j>0)
{
if (inputarray[j-1] > inputarray[j])
{
int temp = inputarray[j-1]... |
I'd like feedback on my revised code after my previous question.
The goal is to create a module which can display, update, save dictionaries as .csv files. I'll use this in another program to update its settings.
I'm learning Python so I'm looking for any and all critiques on mechanics and style.
import csv
# Imports ... |
What do you think of the following "utility" :
/**
* Contextualize a method for callback
*
* @param methodName String Method name
* @param context Object Context (this)
* @param mixed OPTIONAL Argument to place at first
* @param mixed OPTIONAL Argument to place at second (etc...)
*/
co... |
I want to check if there is page variable (in URL) and if it is, if it's correct - it cannot be number 1 because this is default page and it should be valid int from 2 to max number of pages (not octal and not hexadecimal).
<?php
$_GET['page'] = '01'; // this line is only for testing
$selPage = 1;
$totalPages = 10;
... |
I have 2 code block to do same a work and have same target create some thing, but I don't know which block is the best (I mean LINQ or non-LINQ)?
First of all, can anyone tell me how to optimize on the code blocks? And the lastly, help me find the best style between LINQ and non-LINQ:
First block is:
if (tblone.Rows.C... |
I have an implementation of Producer-Consumer multi-threaded interaction. It works, but I feel that during the execution wait states happen too often between Consumer thread and Producer. In my case, Consumer accesses a queue at random intervals and takes data from it. Now, the producer thread runs during the whole p... |
In a user registration form, the validator currently checks not only user input, but also whether or not the user exists. This seems like business logic, which in terms of design should be in the service layer in a "save user" type method. On the other hand, it is highly convenient to keep it in the validator.
Should t... |
I wrote a C++ program for 99 Bottles of Beer, but it's kind of messy. Is there any way I can make it short and cleaner and more easier to read?
/*
* Write a program that prints out the entire lyrics to a full rendition of "99 bottles of beer"
*/
#include <iostream>
using namespace std;
int main (void)
{
int bo... |
I wrote the following function for the purpose of reusability:
template<typename T>
bool contains(vector<T> v, T x)
{
if (v.empty())
return false;
if (find(v.begin(), v.end(), x) != v.end())
return true;
else
return false;
}
Is this the correct way to do, oor is there... |
I am writing a program that utilizes a third party API. I attach a handler to an object and wait for a message back. the responses from the server then get saved into an array list. Unfortunately it takes time for my program to contact the server and so if I make reference to the array list before the server has time t... |
I recently came across a problem where a number \$x\$ is given and I have to find \$y\$:
\$y < x > 1\$
\$y\$ can be expressed as \$a^3 + b^3\$ (more than one combination)
Example:
If 4105 is \$x\$ then 4104 is the answer, where 4104 can be expressed as \$16^3 + 2^3\$ and also \$15^3 + 9^3\$.
I am able to write a pro... |
My final version is a direct translation from Python. Thanks to build-in support for generator, its speed is almost the same as Python. As I quite like using generator and list comprehension in Python, I am not sure I get the right way in Racket.
Moreover, I've only found explicit support for generator in Racket these ... |
When onSaveInstanceState() is customized it should always call the same method on the super instance first.
I usually write:
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveState(outState);
}
private void saveState(Bundle outState) {
outState.putParcela... |
I was wondering if there could be an easier or simpler way of filling a table with code behind.
So far I have my html/asp.net table :
<table style="width:275px;">
<thead>
<tr>
<th><asp:Label ID="LBL_StatsH0" runat="server" Text="Section"></asp:Label></th>
<th><asp:Label ID="LBL_Stat... |
By adding more and more features to my websites, I am now up to 7 different hard coded queries.
I have read a lot about SQL injections and possible flaws and security issues, and wanted to make sure that it was secure enough.
This is one of my regular UPDATE queries :
Using thisConnection As New OleDbConnection("Provi... |
This methods solves for the zero of an arbitrary function using the Bisection Method. It works as desired, but I want to know if the code can be improved or made more readable and if I'm properly dealing with the various error conditions that might arise.
/// <summary>
/// Finds the input value of a function such that ... |
When I work with SqlDataAdapter, I usually follow this pattern. Especially note the using/fill combination, which is basically a one-liner. The other stuff is just the facility around it.
private void PopulateData(DataTable table, long index)
{
SqlCommand command = new SqlCommand(
commandText.Replace("{ID}", "" +... |
In use cases where web applications utilize ng-repeat heavily and also rely on event triggers for each item in the collection, such as ng-click and the like, watchers become too numerous and may adversely affect performance when the number of items grow large.
To remedy this problem, an event delegation directive could... |
I've got a 'menu' within a Master page which include a number of image buttons with click events.
Within each click event, I want to redirect the user to a specific page. However, if the user is already on the correct page, I don't want to refresh the page.
In the example below, if the user is already on browse.aspx, ... |
I'm working on a set of PostgreSQL helper classes, and am representing each PostgreSQL data type as objects. Instead of creating a class for each number format, I've created a template so the user can create a Number<int>, Number<double> etc as necessary, which is awesome as it saves me lots of coding!
The problem I'm ... |
I am starting a personal project and my first step is to insert a lot of statuses from tweeter in a database along with it's user and place (if applicable).
This is the database structure:
Pretty much a user or a place can have many statuses.
What my main question is, is since I'm new to JPA if I'm using an efficient ... |
Inspired by a SO post, just as an exercise, I tried to implement a way of notifying a consumer of a class about whether a property on an object has changed or not. I'm not attempting to use this in anyway, but I would like to learn from it.
interface INotifyPropertyChanged
{
function PropertyChanged($name);
fu... |
My code is for a simple "cart-creation" class and sample use in SFML. The Cart class inherits sf::RectangleShape and will end up having more member functions (isFull, numberOfWheels, etc.) There will also be a conveyor belt class in the transvac folder. Currently, though, the Cart class is really just a special sort of... |
I use this method to check if two reference types are equal
public static bool AreEquals<T>(T source, object obj) where T : class
{
if (ReferenceEquals(source, obj))
return true;
var convertedTarget = obj as T;
if (ReferenceEquals(convertedTarget, null))
return false;
List<obj... |
Is this the correct way to cache a generator in Python, without iterating over it right away (for example using list() over it)?
@property
def results(self):
def caching_iterator(it, r):
for t in it:
yield t
r.append(t)
if self._results: # _results is [] initially
retur... |
I'm just trying to be more pythonic in my coding style and was wondering if this is a good way to get a list of seven days leading up to and including endDate:
daysDelta = 6
lastSeven = [endDate - datetime.timedelta(days=daysDelta)]
for x in range(1,7):
myOffset = daysDelta - x
lastSeven.append(endDate -... |
I'm writing a method that generates a random integer array that are sorted. It takes the arguments of min value, max value and the length of desired array. So for example the arguments with min val = 1 max val = 10 length = 5 could give [1,1,2,3,5,6,9,9,9,10] or [2,4,5,6,6,6,6,6,6,8]. Let me know if the specifications ... |
This function's objective is very simple. It takes array and checks if val is a value inside of this array. It returns whether val exists and which is the index inside the array that contains val.
Could this be coded in a better way? How would I implement this to work with any kind of array (the code below works only... |
I'm looking for some feedback on my OCaml implementation of some methods to translate infix expressions to postfix and then evaluate them.
I'm very new to OCaml, coming from C#/Java and JavaScript so pretty much any advice is appreciated, in particular how to make it more idiomatic or "functional".
It seems like I hav... |
I have been thinking about this aspect of my game for a little while, and I have come up with the following solution. I am sure that there are problems with the way I have implemented it so any kind of feedback would be very helpful.
The idea is that there are a number of different variables in the game that together ... |
Here is a namespace for wrapping boost accumulators for use in a broader code base. I love these accumulators but re-typedefing them everywhere is ugly and a pain.
I am not interested in C++11 alternatives. My code base does not put the starting bracket on a new line. My code base uses doxygen. Most of the style choice... |
I have been building a small library of VBA functions. I have a small section with higher order functions that I'd like to share. It uses strings as delegates/function pointers and Application.Run to actually call the functions.
This isn't by any means a true implementation; just a quick and dirty implementation with... |
Write a function AlternatingSplit() that takes one list and divides its nodes to make two smaller lists a and b. The sublists should be made from alternating elements in the original list.
Example: if the original list is 0->1->0->1->0->1, then one sublist should be 0->0->0 and the other should be 1->1->1.
This code ... |
I recently coded this FNV-1a hash function in Lua. Are there any apparent performance improvements that could be implemented?
local bit = require(game.ServerStorage["luabit-0.4"].bit)
-- External library
local hex = require(game.ServerStorage["luabit-0.4"].hex)
-- External library
local FNV_Primes = {
[32]=2^24+2^8+0x... |
I've just started learning R, but I feel that I'm using it only as a normal procedural language without taking advantage of some built-in functions and data structures.
I wrote a function that calculates repayments for mortgage with an option of specifying list of overpayments to reduce monthly payments. Please sugges... |
I have some neural network Julia code which I'm hoping to speed up. It's possibly simply poorly-designed, but I'm not convinced.
# This is line 1 (for the purpose of matching the profiler output's line numbers)
sigmoid(z::Float64) = 1/(1 + exp(-z))
sigmoidPrime(z::Float64) = sigmoid(z) * (1 - sigmoid(z))
### Types #... |
I have a button (or icon) which can have three states.
On hover, it changes state and on click, the new state gets transferred to another state. This state is kept until you click again for which it gets back to normal.
The code is working, but it does not look or feel good. Is there any way I can re-factor this?
Fidd... |
I'm working on a simple online dictionary tool, using Python Flask-RESTful as the RESTful API backend. The dictionary tool is modular, it can handle multiple dictionaries, implemented as independent plugins.
I have API endpoints like this:
/api/v1/dictionaries/:dict_id/find/exact/:keyword
/api/v1/dictionaries/:dict_id... |
What's the best way to approach generating a password using a secure prng? In Python, I could simply use os.urandom. Any suggestions on this?
_ = require('underscore')
exports.gen = (n=10) ->
throw new Error 'Not a number!' if typeof(n) isnt 'number'
throw new Error 'Prefered (n): [10..128]' if n < 10 or n > 128
... |
I often face the problem of stacked if-statements that look repetitive, but usually can't find an easy way to simplify it.
if (keyState[BOTTOM]){
dig_direction = BOTTOM;
startDig(SIZE / 2 - x % SIZE, DIG_DEPTH);
} else if (keyState[RIGHT] && isTouching[RIGHT]){
dig_direction = RIGHT;
... |
I'm not doing too well in school, so to pass my final year, and get my degree I need to do an off-school project. The teacher chose to give me the assignment of an A grade CMS, since I've always had a thing with PHP.
Now I've made a new template class for in this particular CMS, but I'm not completely sure about it, so... |
I'm working with some data on college students, which has a unique key of SSN, Campus, Credential (type of degree sought, like "Bachelor's"), ProgCat (broad subject area, like "History"), Program (specific subject area, like "European History"), and SchoolYear. I want to calculate a lot of statistics (for the sake of t... |
Array.prototype.unique = function() {
var a = [], // uniques get placed into here
b = 0; // counter to test if value is already in array 'a'
for ( i = 0; i < this.length; i++ ) {
var current = this[i]; // get a value from the original array
for ( j = 0; j < a.length; j++ ) { // loop an... |
I have written a function that gets a function as input (acquired from numpy.poly1d). The function has access to the GUI variables self.batch and self.inputFile, these variables specify if the function is called in batch mode or not and what the current inputFile (for transformation is).
My main concerns are:
Would yo... |
Recently I started looking at my AJAX call security and found some code that uses tokens, request and referer in an attempt to authenticate the call and stop XSS and CSRF.
The AJAX calls are for the article list / article table in the admin section.
Note: The PHP will not run unless you are logged in — it uses a cookie... |
I wanted to write a generic abs function that would correctly work for every type. Basically, I wanted to use the following algorithm:
If the type is a built-in integer, use std::abs from <cstdlib>.
If the type is a built-in floating-point, use std::abs from <cmath>.
If the type is a user-defined type with a namespace... |
I made this class, just to understand what PSR autloader is. I didn't want to download and use it without knowing how it works. So, the one I built is very simple, but I would like a review on how to improve it, and what it lacks to be 100% psr-1 compliant.
Here is the class loader.
namespace ClassLoader;
class Loa... |
Exercise 5.17:
Given two vectors of ints, write a program to determine
whether one vector is a prefix of the other. For vectors of unequal
length, compare the number of elements of the smaller vector. For
example, given the vectors containing 0, 1, 1, and 2 and 0, 1, 1, 2,
3, 5, 8, respectively your program sh... |
I was in an interview and the guy asked me to do the typical FizzBuzz question of printing numbers 1-100, but for each factor of 3 print Fizz, each factor of 5 print Buzz, and each factor of both print FizzBuzz. I wrote the following:
public static void fizzbuzz(){
for(int i=1;i<=100;i++){
if(i%15 == 0){
... |
I've implemented an external mergesort to sort a file consisting of Java int primitives, however it is horribly slow (fortunately it does at least work).
Very little happens in the sort method: it just recursively calls merge with blockSize doubling each call and swapping input and output files each time.
How could I b... |
I took the question Performing insertion sort in C# and tidied it up a bit, then I thought about the use of the arrays and was wondering if it worked, and it does.
So now I have 3 static methods in a simple Program class to run from the console, just to check 15 numbers quickly. It's not very efficient.
What can be ... |
I use at to schedule jobs and atq to display the scheduled jobs. But it mildly irritates me in that I have to look up each job individually. I wrote a Python script to display the scheduled job under the scheduled time.
(In my world all the commands will begin 'task')
So instead of
stafflinux$atq
8 Mon Aug 18 09:... |
I am quite new to Ruby, coming from a JavaScript background. I wrote this simple Ruby script that finds whether two strings are anagrams or not.
To run it: ruby ruby_anagrams.rb 'script1' 'script2'
I am looking for comments and a code review on my script. Can I do anything better? Is this good Rubyism?
# removing whit... |
I have a complex phone validation that does the following:
First, check if either a home phone, mobile phone or work phone is provided (there will be 3 text fields in form and at least one type of phone number is required).
Strip out any characters from the phone number that is not a digit except 'x' and '+', since th... |
When I want to check the validity of an attendance being entered into the system, I perform following action.
AttendancePresenter Class
void _View_OnCheckValidity(object sender, EventArgs e)
{
//ExecuteAction performs exception handling in Base Class
this.ExecutAction(() =>
{
... |
I have a method that generates a sorted array with random values in a given range. I wanted to make a method that does this but in descending order.
The easiest way to accomplish this is to call the first method that generates a sorted array and then reverse it. I believe the simplest way to reverse the array is to cal... |
On advice from an answer to my previous question, I have written some code that will allow my game balance properties to be loaded from a remote server. Right now I am just hosting the raw property list file on a web server for simplicities sake.
My first question is whether there are any long term problems associate... |
This HTML code seems to work: the page looks as I intended it. I have checked it multiple times, but it's difficult to tell how to improve. I would like somebody to review and point out any mistakes or bad practices, or other recommendations to make it better.
This is to be output as an email:
<!DOCTYPE: html><!--... |
I've been working on a little project on an Arduino and I need some help with making the code more efficient / cleaner. I really don't like the three for loops and feel like I could condense them somehow.
How it works:
An HC-05 Bluetooth module is connected via a serial connection to an Arduino Micro.
The Arduino filt... |
I wrote a game loop for a game I'm going to be making:
Check the current FPS
Try the keep the FPS to a hardcoded level
Draw and Update the game.
There are two classes, the abstract class and the implementing class.
Any suggestions?
Game
public abstract class Game {
private int FRAMES_PER_SECOND;
private boole... |
What I'm trying to accomplish is to have a error checking class mostly to check if parameters that are pass null but also data structures within class are not null. So my thought is a clean static method call to pass these variables and verify if it's valid, and if so, return a boolean.
For example, my code is seems t... |
Given a singly linked list, swap kth node from beginning with kth node from end. Swapping of data is not allowed, only pointers should be changed.
This code is attributed to geeksforgeeks. I'm looking for code-review, optimizations and best practices.
Why I don't extend or reuse: I am prepping for interviews, and... |
I had asked questions about my entire class which I'll flag for closing soon. It appeared to be a little too broad for 1 post so I chopped it up and will be asking a little more specific questions separately.
In my Application Layer I have a class AuthService containing the following method with a code structure that ... |
I was recently asked to write a Question-and-Answer feature for my company's product pages using Yii 1. It was my first Yii project, and it was a little rough around the edges (Code A). However, when I submitted my code, my boss rewrote my two actions to a single action (Code B).
Both Code A and Code B work, but, in ge... |
I want to ask whether is good practice to have single instance of database connection or declare new every times when we needed? I have this two designs shown in below:
This is database class:
<?php
class Database extends PDO {
//Variable declaration
private $host = "localhost";
private $passwd = "";
pr... |
I am creating a HTML game where you fight monsters and stuff and this is part of the game loop for dealing damage:
var hp = 1000000000;
var speed = 10;
var power = 5;
var lastCalledTime;
var fps;
var GameLoop = function() {
if(!lastCalledTime) {
lastCalledTime = new Date().getTime();
fps ... |
Which of these approaches for a button click is better/faster/more efficient, and why?
Approach One:
Button button = (Button) findViewById(R.id.button_english_splash);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
... |
I have a CSV file with 400 000 rows and the following headers:
header_names = ['LEAGUE', 'YEAR', 'DATE', 'HOME', '1', 'X', '2', 'AWAY', 'SCORE', 'SCORE_1', 'SCORE_2', 'FTR', 'FAVORITE', 'UNDER-OVER']
The aim of my function is for every row to take all the previous, filter them by items in the current row and return s... |
I had just finished work on the Memento Pattern, and now I want to hear your feedback on it.
public class Caretaker {
List<Originator.Memento> snapshots;
public Caretaker() {
this.snapshots = new ArrayList<Originator.Memento>();
}
public Caretaker(List<Originator.Memento> snapshots) {
... |
I like to know if there will be any performance issue if an xmlhttp object is created every time. For example, in the below code:
function currentTime(){
var obj = null;
if(window.XMLHttpRequest){
obj = new XMLHttpRequest();
} else {
obj = new ActiveXObject("Microsoft.XMLHTTP");
} ... |
I am writing an application with Java 8 using NetBeans, and want some reassurance that I am going the correct way with this.
I am finding it tough because of the use of Swing.
I have gone for one model (for now), one controller and a set of views. All of the MVC examples for Java/Swing involve one JDialog, one model an... |
I wrote a simple AJAX request that performs a random select in two MySQL tables. My current script involves connecting to the database and creating a new PDO every time the #generate button is clicked.
Can it be considered a bad practice? Could it lead to performance issues? If not, how could it still be optimized?
PHP... |
I created this custom binding handler:
ko.bindingHandlers.line = {
update: function (element, valueAccessor, allBindings) {
// First get the latest data that we're bound to
var value = valueAccessor();
// Next, whether or not the supplied model property is observable, get its current value
... |
Here I'm trying to develop a simple framework for my own purpose. I'm using PHP and PDO. But, I'm still worried about my password security codes. Below I have posted my codes. it stored like these in my database $1$sr1.F90.$hXd.9DheSMtYmI52KT7fy0. Is this the right way to store passwords? Or Am I make anything wrong he... |
I have to sort many large numbers in a given time limit. The program below works, but not when the test cases reaches \$10^6\$, in which case it exceeds the time limit.
def tsort(tests)
sorted_array = []
1.upto(tests) do
input_num = gets.chomp.to_i
sorted_array[input_num] = 1
... |
I am working on my Tritium website (hosted on Github: feel free to fork and send pull requests), and now am looking for a review of it. If you are looking to critique the design of the website, please visit the sister question over on Graphic Design.
Here is what I would like reviewed:
Organization - Can you find wh... |
I put up a simple WSGI static file handler, but I'm skeptical about its efficiency, also because I got a handful of errors while benchmarking it with Apache Benchmark.
The errors are:
IOError: [Errno 24] Too many open files: 'test.png'
Client 101 hit errno 32
Client 601 hit errno 32
Client 408 hit errno 32
Client 225 ... |
Description
Match a Simple Sentence or a partial sentence
Suitable for matching
People Names (to some extent)
Product Titles (to some extent)
Correct use of apostrophe (to some extent)
Input/Result
match("Because I'm Batman") true
match("John Cena's fans") ... |
I'm trying to follow the path of Sandi Metz and others who state that aiming for small and simple is good for writing understandable code. I've written a method that takes care of writing content to a file without overwriting any existing file of the same name. I wrote it TDD style and, once the tests passed, I refacto... |
I'm working on the interactive API documentation of a RESTful dictionary service.
The page should let testers try the different API calls,
by playing with the parameters using a simple web form.
Changes to the web form should trigger API calls with the appropriate parameters,
display the JSON output,
and a well-formatt... |
After failing miserably to get SQL to work with Haskell, I decided to try making my own system. It's fairly simple, but works well for simple jobs (I made it to handle highscores for a number guessing game). Its biggest issue is that the "tables" are only 1-dimensional currently, so it's quite limited in that regard.
B... |
I built a small JavaScript function to see if a series of characters are a palindrome or not. The functions works well and does everything it has to do, but I'm wondering if something can be tweaked to make it faster.
This is the actual code:
var words = ['anita lava la tina',' a ', 'civvic', 'ddaa', 'aa', 'dca', '332'... |
Problem Statement
Akash and Akhil are playing a game. They have N balls numbered from 0
to N−1. Akhil asks Akash to reverse the position of the balls,
i.e., to change the order from say, 0,1,2,3 to 3,2,1,0. He further
asks Akash to reverse the position of the balls N times, each time
starting from on... |
The code below is intended to be a learning material for high school intermediate programming class, as an introduction to recursion and backtracking. I was thinking of rook placement and found it too boring. I was also thinking of unique queen placements and found it missing the point.
The code works (verified against... |
I'm merging dictionaries together in series. Each one may/may not have lists as values. I'd like to merge indefinitely and, have the final merged dictionary contain only flat lists as values.
Any advice for how to write this as a single/simpler function?
def merge_dlist(dict_1, dict_2):
"""Merge_dlist accepts dicti... |
My MapReduce tester is clearly ported from Shell, short of args=None for line in args or read_input(), what's a better way of importing->testing the function outside of subprocess?
Or does it not matter, i.e.: my "hack" is fine?
test_mapreduce.py
from unittest import TestCase, main as unittest_main
from subprocess impo... |
Project Euler Problem 12 asks to find the value of the first triangular number to have over 500 divisors, where the \$n\$th triangular number is \$\sum_{i=1}^{n} i\$.
The sequence of triangle numbers is generated by adding the natural
numbers. So the 7th triangle number would be \$1 + 2 + 3 + 4 + 5 + 6 + 7 = 28\$. T... |
I solved this problem using custom functions and calling them in main function. The challenge was to avoid global variables. Please note that I'm C++ noob and this program is fairly large. I'm posting it here so experts can give me suggestion and point out my mistakes for good programming practices.
Is there any bette... |
Can you please give me a hint on how to improve performance of the following algorithm meant to find the number of inversions in a given array?
/* *
* INPUT:
* 1. t : number of test cases; t test cases follow
* 2. n : number of elements to consider in each test case
* 3. ar[i] : n numbers, elements of considered ar... |
I am trying to figure out a way to make finding duplicates in Java more efficient. I started off with this:
private boolean hasDuplicates(int[] array) {
List<Integer> list = new ArrayList<Integer>(array.length);
for(int num : array) {
list.add(num);
}
for(int num : list) {
if(list.indexO... |
What do you think the weak points are and how can I improve? I thought I could really use a Hand class in the dealHand method.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleBlackjack
{
public enum Suit
... |
Is there any MySQL function that will optimize this code?
function get_parents() {
$ids = array();
while($id) :
$query = "SELECT placement_id FROM referrals WHERE user_id = $id";
$query = $this->db->query($query);
$result = $query->row();
if(!isset($result->placement_id)) :
break;
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.