instruction stringlengths 71 71.9k |
|---|
The following code is for a calculator made in ruby, I find that this way saves much time than having to build this calculator from scratch, especially that I want it to support BEMDAS operations. However, I'm feeling that it is inefficient because I'm using eval, and I think this could be dangerous.
Is it a good idea ... |
I'm a senior Comp. Sci. major working on a senior design project for our faculty. The name of this project is "Gradebook", and it is responsible for allowing instructors to record grades for students and for students to check their grades in a class. This project is written in Ruby on Rails, and this feature set is int... |
I recently got a Scala developer position, so I'd like to get more comfortable with Scala on my own. Here is a maze solver that I wrote (previously in other languages) that I translated to Scala. Any tips or suggestions on coding style is greatly appreciated.
Ideone
import scala.collection.immutable.Queue
object MazeS... |
Trabb Pardo and Knuth devised this simple procedure as a way to explore the functionality of various languages. The wiki page describes it as:
The Trabb Pardo–Knuth algorithm is a program introduced by Donald Knuth and Luis Trabb Pardo to illustrate the evolution of computer programming languages.
The algorithm is si... |
We were discussing Standard Deviations in chat, so I decided to write a standard deviation calculator:
static double PopulationStandardDeviation(List<double> numberSet)
{
double mean = numberSet.Average();
return Math.Sqrt(numberSet.Sum(x => Math.Pow(x - mean, 2)) / numberSet.Count);
}
static double SampleSta... |
I needed a simple way to add this test to certain click events:
if isUser then fireClickEvent else openSignInModal
So I made this directive:
angular.module 'openLETS.core.lib.guestLock', []
.directive 'authGuestLock', ($compile, $state, olString, Auth) ->
######### Private #########
restrict = 'A'
priority = 1
... |
Here's an implementation of Hangman that I've written that uses a basic GUI. As I am new to Java, please let me know of any improvements I can make to my coding style. Thanks for your help.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.*;
... |
When I run this function for outputting an inverted index to a text file in Debug Configuration, it takes nearly two minutes (96 seconds) with a comparatively tiny dataset, 1252 records with the longest being 76 entries.
std::ostream& operator<<(std::ostream& out_stream, const InvertedIndex& rhs) {
std::ostringstre... |
This is a bit tricky to explain. I'm trying to model a cyclic iterator that would return the next available DataSource(SQL). So infinite calls would just pick the next source nicely. The new twist comes with the idea that one DataSource might be 'busy' or somewhat. That is abstracted as a 'waiting' datasource. This des... |
I'm just looking for some feedback on my User class. The class is designed to handle users being able to register, login, and logout of the site. I'll be using it in conjunction with a forum I'm also working on.
I'm mostly curious how I've handled validation of input, MySQLi interactivity, and whether my code is redund... |
I'm in the process of a complete re-write of a stagnant and ill-conceived project. I would like some feedback on the following Python 2.7-3.4 code, before I go any deeper into it.
I would hope it is self-explanatory, but that is always the illusion when you stare at something long enough. The other dilemma is glossing ... |
I'm new to PDO and haven't been coding in a while. Is the following custom session handler industry-acceptable?
class Session {
protected $sdb;
function __construct() {
session_set_save_handler(array($this, '_open'), array($this, '_close'), array($this, '_read'), array($this, '_write'), array($this, '_... |
This is a script that utilizes lazy exception throwing. What I do is decorate a function that might throw an exception to throw an exception with a formatted string.
from functools import wraps
def on_fail(message):
def on_fail_dec(func):
@wraps(func)
def on_fail_wrapper(*args, **kw):
... |
I've been fiddling with Unity, trying to make nice walking/running animations. So, i found the Stealth tutorial and I used pretty much the same animator as the AI, only I only use Speed and AngularSpeed and, of course, added a control script. The controls work as intended but the whole script is laggy. I know, my Updat... |
Given a limit \$n\$, find all the pairs of values less than, or equal to n, which have the the property:
pair(a,b)
where a = sum of divisors of b
and b = sum of divisors of a
I need to speed up my double for-loop but I don't see how to do it in this case.
def diviseurs_propres(n):
t = [1]
for i in range(2... |
I'm working on website with a parallax effect. The jQuery code is working, but I wonder if there could be made any improvements made to the code. At the moment it works totally smooth in Firefox, but in other browsers it seems to be a little bit jumpy. Also, the effect is not working in IE 9.
(function($) {
var $con... |
The following is code on "prime factors of a number". Any suggestions to optimize the code? It runs for a pretty long time for inputs like 35068499. I also want the code to take 10 digit numbers as input.
#include<stdio.h>
void pf(long);
void main()
{
printf("Enter a number: ");
scanf("%ld",&n);
pf(n);
}
vo... |
This code works, as far as I can tell, but there's something that just feels wrong about it. The intended flow is like this:
If no dialog is showing
Show dialog, return result
else
Move dialog into view, return no result
It sounds easy enough, but because there's a possiblity of multiple threads I have to use loc... |
I want to map values of a enum to some other values. For instance, here I map Color to Group:
enum class Color {
Red, Green, Blue, Cyan, Magenta, Yellow, White, Black
};
enum class Group {
Primary, Secondary, Neutral
};
One particular interesting case is to map enum to a string (serialize), but I'm interested in t... |
I wrote a Perl script to implement a simple menu where you can call subroutines for each menu option. I created a Menu class that can be used to create new menus and a print method that will start the menu.
Is there any way I could simplify this?
# Menu.pm
#!/usr/bin/perl
package Menu;
use strict;
use warnings;
# ... |
I have recently started using browserify and have created a custom module to toggle two menus based on the ID clicked and apply a transparent overlay effect behind the menu. I have got it working but just wanted to get some feedback on weather it can improved performance or coding wise as I am wanting to improve my JS ... |
I need to be able to accept some options from either the command-line or a config-file.
This code is a snippet of the class that I am working on, I cannot post the entire class here. This code works, but I am wondering if it can be made better. I will need to have a class here, there is a lot more work that goes on in ... |
As a Java programmer who's trying his hand at C++, I thought I'd start building a library for working with matrices as my first C++ project. I've got very little C++ experience and it's been a long time since I've even so much as dabbled in it.
So far I've only implemented an addition function, but I think this should ... |
I'm new to Python and wondering what can be improved with the following super novice program - in terms of the solution and code style etc.
test_fizzbuzz.py
import unittest
import fizzbuzz
class TestFizzbuzzFunctions(unittest.TestCase):
def test_it_converts_multiples_of_three_to_fizz(self):
self.assertEq... |
I was looking for a way to perform additional tests before waiting for an event:
if everything_is_alright():
event.wait()
But this is not thread-safe. A correct version would be:
with lock:
wait = everything_is_alright() and not even.is_set()
if wait:
event.wait()
The problem is that the lock have to be a... |
This is not the latest question in iterative code review of this program. You can find the latest answer here.
Here's my solution to Project Euler #54. Click the link for the full project description (abbreviated here):
The file, poker.txt, contains one-thousand random hands dealt to two players. Each line of the fi... |
There are many ways to shuffle lists; for example, Racket's built-in shuffle assigns each list element with a random number as a sort key, then sorts the list, which provides an O(n log n) runtime. However, I'd like something that's O(n), and that's where Fisher-Yates comes in.
Fisher-Yates is designed for use with ran... |
I get the feeling the code for this to-do app is not secure. I am just a beginner, and I don't know much about coding style so do you think it is conventional/elegant?
Please don't hesitate to criticize my code.
/*global require*/
/*global console*/
/*global __dirname*/
(function () {
'use strict';
////////////... |
(from McDowell) Given a sorted array of strings which is interspersed with empty strings, find the location of a given string.
eg. "ball" in
{"at", "", "", "", "ball", "", "", "car",
"", "", "dad", "",""}
would output 4
Any comments on the code below?
Also, correct me if I am wrong please:
- space complex... |
This is my solution to find the Number of distinct elements in an array. Is there away fast way to do this? It run-time is O(N).
public int DistinctNumberOfItems( int[] A ) {
if (A.length == 0) return 0;
if(A.length == 1) return 1;
Set<Integer> set = new TreeSet<Integer>();
for (i... |
The following XAML is a close (tidied up) version of what I have use in my WPF application. If you have noticed there are two Styles applied to the same component (Border in this example.)
I would like to know how can I merge the 2nd Style into 1st to make it apply to all the Borders included in the DataTemplate.
<Data... |
This is a challenge up on Programming Praxis, however there are no Java solutions, and there are few Java implementations elsewhere on the internet.
Most of these implementations simply search the grid for the words that the user is supposed to find. This program finds ALL of the dictionary words that are in the word ... |
Your mission, should you chose to accept it, is to beat everyone else to the review tab so you get a chance to help out.
This is a problem I've been running into lately. I go over to review tab, find a post awaiting review, select it, and then after my page loads, it's already been reviewed.
And since this site does... |
I'm currently building some software that works with systemd unit files, and I've been trying to improve how we construct the unit files.
This is all running in Python 3.4
This first block is the base classes I'm building things up with.
class LimitedDict(dict):
"""
Sub Class of the dictionary object that rest... |
I have a pandas DataFrame and a (MySQL) database with the same columns. The database is not managed by me.
I want to update the values in the database in an "UPDATE... WHERE" style, updating only some columns wherever some other columns match.
Here's my code:
import sqlalchemy as sqla
def save_to_db(final_df, passwd):... |
I was looking for a way to write to and then read from a file in different parts of my code, without passing the filename around and without consumers needing to know it was coming from a file.
I came up with this FilePipe based on io.Pipe:
package pipe
import (
"io"
"os"
)
func FilePipe(name string) (*io.Pip... |
I'm practicing for a contest by doing some of the older problems, and I was wondering if there are more efficient ways of doing this or if I'm not following any coding conventions. Most importantly, I would like to know if I am using ArrayList correctly in this code, since I learned how to use it off of a brief tutoria... |
I was trying to solve this problem in Java:
Given a 2-D array of black and white entries representing a maze with designated entrance and exit points, find the shortest path from entrance to exit, if one exists. The black entry represents a wall and the white entry represents an open space.
I tried to solve it using ... |
I was reading Knuth's The Art of Computer Programming - Volume 2 (Seminumerical Algorithms) Third Edition. I saw the two algorithms (A and B). A method (due to V. C. Harris) was mentioned (in page 341), which I quote:
V. C. Harris [...] has suggested an interesting cross between Euclid's algorithm and the binary algor... |
I wrote this code for checking checkboxes. There are two groups of checkbox: each group's checkboxes have one common class all_perks and one individual class perks and perks_admin.
When any checkbox is clicked:
It will check for same amount checkbox in same group and check them, search for same amount of checkbox in o... |
I'm using ConcurrentDictionary to hold the records.. I'm reading files from the local system in parallel, to speed up the process.
Sample 1:
static ConcurrentDictionary<Int64, Byte[]> concurrentDictionary = new ConcurrentDictionary<Int64, Byte[]>();
private void ReadFilesFromDirectory()
{
string[] docNames = Directo... |
Trying to get to grips with Haskell. The problem is taken from here.
{-
Given Credit Card number: 49927398716
• Reverse the digits: 61789372994
• Sum the odd digits: 6 + 7 + 9 + 7 + 9 + 4 = 42 = s1
• The even digits: 1, 8, 3, 2, 9
• Two times each even digit: 2, 16, 6, 4, 18
• Sum the digits of each multiplicat... |
I am creating a CMS for a website, so I've added most of the functions that will fetch data from the database to a separate class. The code doesn't seem to have any bugs(Since I've tested it) but I don't like the way how it's looking, I feel like it can be improved but I don't know how. The other concern I have is whet... |
I use the following code and I want instead to repeat it over and over again
to write it in short/better way,is it possible in JS?
runCo.addContent(oTtlLo);
runCo.addContent(oLblP);
runCo.addContent(oAcFileP);
runCo.addContent(oTvFiL);
runCo.addContent(oTtlP);
and I've more then 10 lines more for ... |
This is the Perceptron algorithm, I wrote this implementation with my friend. It gets the job done, but it's quite dirty, perhaps one of you stylish hackers might help me beautify this beast.
This is what I made to generate my data structures and run everything:
public class FileDictCreateur
{
static String PATH ... |
This is my second solution to Project Euler #54. You can find the original post here.
Brief problem summary:
The file, poker.txt, contains one-thousand random hands dealt to two players. Each line of the file contains ten cards (separated by a single space): the first five are Player 1's cards and the last five are Pl... |
For a large, multi-threaded video processing application, I need to manage various child processes. I need to monitor their stdout and stderr.
My key concerns:
I should not have any spin loops. I have a Thread.sleep(10) on my inputHandler (... which is actually a process output handler, but okay), but that's because i... |
In my application, I need to allow the user to store variables. Variables can only be of specific types, but I effectively handle all variables the same way no matter the type. I would also like to avoid any casting. Therefore, I have several HashMaps for each variable type, which is causing lots of duplicated code.... |
I'm using a Telit GE864-GPS modem, which runs a dialect of Python 1.5.2. The Python module has access to the modem using a buffered UART, which may still be receiving when reading starts. The following code makes sure the entire response is read, and return either the response body or '0' on timeout.
def receiveReponse... |
I am a newbie trying to learn some Java and I am reading prof. Dan Grossman's introductory lecture notes on parallel and concurrent algorithms.
I wrote a version of a divide-and-conquer algorithm for summing an array of integers using both bare-bones Java Threads and one that uses the new (in Java 7) Fork/Join framewor... |
Some of you may have seen my previous post asking if my code was efficient and easy to read.
I have made some more improvements to it by adding sounds, visual count down and checking if the window has focus. Before I carry on with my program I would like to know if this is efficient and easy to read.
Here is the zip fi... |
I have created a little program to search a set of folders holding documents scanned.
The folder structure is as follows:
c:\images\year\month\date\documenttype\firstpartofdocumentNo.\
the year folder contains years from 2005 - 2015
the month folder contains the months of the year (Obviously) same with
date
the docu... |
I'm learning Scala and could use another set of eyes on the code below. I'm creating a test runner for the 99 scala problems set. I figure between actually solving the problems and working through the pains of setting up a new IDE (trying IntelliJ from Eclipse), using new build tools (trying SBT from Maven), new testin... |
I'm used to only processing, at most, one line of a file at a time. This is my first time changing the delimiter, and the objective here is to take a file containing lines such as:
Bubbles,
Blossom and
Buttercup
Nostalgic
Examples for the
Win.
Quick Brown Fox
Jumping Over Lazy
Dog.
and produce single l... |
I wrote a program that calculates gross wages for employees. The program asks the user enter an employee's ID, hours worked and hourly pay rate. It then calculate the gross wage for that employee and store this employee’s information into a file, chosen by the user. It then asks the user if they would like to show the ... |
I have just started learning functional programming (Haskell) for fun after using imperative languages my whole life. I am looking for quick and simple tips from pros on how the particular code I just wrote (a simple program solving a simple task - factoring an integer) can be simplified and made more beautiful.
-- Fac... |
I have implemented both a brute-force and a heuristic algorithm to solve the travelling salesman problem.
import doctest
from itertools import permutations
def distance(point1, point2):
"""
Returns the Euclidean distance of two points in the Cartesian Plane.
>>> distance([3,4],[0,0])
5.0
>>> dist... |
When a LivingBeing attacks another LivingBeing, an attack roll is made to determine if a hit occurs. If a hit occurs, a damage roll is made to determine the amount of damage.
The task is to find a design so what the attack roll and damage can be adjusted no matter how many exterior objects affect them and no matter ho... |
I'm a little confused as to whether implementing the Dispose method serves a purpose in this code. It never gets referenced by any other class in my project, so should I simply get rid of it or should I make an explicit call to Dispose when releasing the bitmap image?
namespace ImageProcessor
{
/// <summary... |
So I have this problem, where I'm given m connections over n vertices. The vertices are labeled 1...n.
Example input:
4 5
1 2
2 3
2 4
3 1
3 4
The first row contains the numbers n and m. The following m rows tells me what connections exist. It's safe to assume the connections contain every number 1...n at least once.
T... |
I have a big array of custom flat colors with perhaps 100 lines:
extension UIColor {
class func randomFlatColor() -> UIColor {
let colors = [
UIColor(red: 210/255, green: 77/255, blue: 87/255, alpha: 1.0),
UIColor(red: 217/255, green: 30/255, blue: 24/255, alpha: 1.0),... |
This challenge posted by Durron597 intrigued me, and inspired me to answer his question, and also to determine whether a more functional approach was available for poker hand ranking.
The problem description is:
The file, poker.txt, contains one-thousand random hands dealt to two players. Each line of the file contain... |
This code was inspired by this question: Payroll Program. I saw lots of ways I thought the code could be improved. So much so that I thought it wouldn't be particularly constructive to post all of it as an answer to that question. Essentially, I wanted to basically rewrite the whole thing from scratch.
So I did. Bu... |
I am working with an undirected, weighted graph. It contains two types of nodes, called "A-type" and "B-type". I am starting with a set of tuples of the following form that describe the graph edges:
(string: Name of First Node, string: Name of Second Node, float: Weight)
Example graph:
My goal is to reduce the graph... |
I have a class that takes an array of integers and produces a multiplication table.
class MultiplicationTable
def initialize(num_ary)
@num_ary = num_ary.to_a
end
def generate
a1 = @num_ary.clone
a2 = @num_ary.clone
rows = []
rows << a1 ... |
I am trying to learn C and I came across the ROT13 scrambling system used to store some passwords.
Assuming the user types everything in correctly (uses 1 argument, uses a string not an int, etc.) would this be correct/safe to use? Or is there anything at all that I am doing wrong you can point out to me (techniques, i... |
Find an element in a MxN matrix where each row and column is sorted in ascending order.
Any comments on my code?
(I added some test cases on non square matrices which I did not copy here)
import static org.junit.Assert.*;
import org.junit.Test;
public class Sol {
public class Coord{
int x;
int y;
publ... |
A program to simulate a linear linked list using an array:
Specs:
A y : Create a new node with data value y, and append this node to L
I x y : Find the node t with value x, create a new node p with data
value y, and insert node p after t in L
D y : Find the node with data value y, and delete that node from L
R : R... |
I am trying to split my list into a dictionary and I wrote a function for it. It takes in a list and gets the list length. If the length of the list is 253 , it creates a dictionary with 26 keys - this is calculated by rounding up the number to a higher 10 (250 will create 25 keys, 251-259 will create 26 keys). Each ke... |
My code have too much nested option processing which makes it ugly. But it has an advantage it has no side effect and typesafe.
package repos
import java.io.{InputStream, File}
import org.apache.poi.hssf.usermodel.HSSFWorkbook
import org.apache.poi.ss.usermodel.{Cell, Row, Workbook, Sheet}
import org.apache.poi.xssf.... |
This code has loops under loops which affects the performance badly. Please help me to optimize the code to improve its performance.
private void processPlainOutputFormat() {
// we reached the end of corpus processing.Process all Documents from corpus
Iterator<Document> documentIterator = getCorpus().iterator()... |
This was a challenge for reddit #202 Easy /u/learnprogramming ...I wish that someone reviews my code and let me know your opinion about my way of thinking beacause I am a total beginner in Ruby:
class BinaryChar
attr_accessor :binaryString
def convertToChar
binaryString.scan(/.{1,8}/) { |part| print part.to_i(... |
I have to recursively solve the following problem, using a brute force approach:
Suppose two people, A and B, have an even number of ordered boxes, each with a given value. For example, boxes = {5, 3, 7, 10}. They need to split the boxes between them, in this way: person A chooses either the first or the last box in th... |
I often want to iterate either row-wise or column-wise though a matrix in Julia, so I've created a pair of functions to help:
function cols(x::Matrix)
function _it()
for ii in 1:size(x,2)
produce(x[:,ii])
end
end
Task(_it)
end
function rows(x::Matrix)
function _it()
... |
After this question, the next part.
Coding to the same interface as the previous question:
Note: Since not every system has libyaml installed, the config script tries to detect its existance and sets HAVE_YAML if it can be found (see autotools detect yaml library).
YamlParser.h
#ifndef THORS_ANIVL_SERIALIZE_YAML_PARSER... |
These are some macros to help build a traits class (for the parser/printer classes I am building).
Traits.h
#ifndef THORS_ANVIL_SERIALIZE_TRAITS_H
#define THORS_ANVIL_SERIALIZE_TRAITS_H
#include <string>
#include <tuple>
/*
* Macros for counting the number of arguments
* Currently set up for a max of 20.
*/
#defin... |
Here is my code to reverse link list in using recursion:
Node n = null;
private void ReverseList(Node temp)
{
if (temp == null)
return;
ReverseList(temp.nextNode);
Node newNode = temp;
newNode.nextNode = null;
if (n == null)
{
n =... |
I wrote this code to read from a CSV text file (containing data such as 12,3,568,48,3,8 with no more than 3 digits to each number). It stores the numbers as char arrays in the vector values. However, this does seem like a clumsy way of doing this with resizing the vector and copying the chars. Is there a neater/more su... |
I have a challenge:
In Sweden, there is a simple child's game similar to Pig Latin called Rövarspråket (Robbers Language).
In the CCC version of Rövarspråket, every consonant is replaced by three letters, in the following order:
the consonant itself;
the vowel closest to the consonant in the alphabet (e.g. d → e), wi... |
I currently override the sorting methods provided by namedtuple by doing something like this:
class Subtitle(namedtuple('Subtitle', ['index', 'start', 'end', 'content'])):
def __eq__(self, other): return self.start == other.start
def __ne__(self, other): return self.start != other.start
def __lt__(self, oth... |
I have a simple .csv file with ~400,000 line (one column only). It takes me a lot of time to read the records and process them.
The processor validating records against couchbase. The writer - writing into remote topic, takes me around 30 mins.
I read that flatfileItemreader is not thread-safe, so my chunk value is 1. ... |
Below, I have created a rudimentary script to decipher a columnar transposition. I am wondering if there is a more efficient way to determine the number of the rows in a column? Also, is there a way to build the resulting string without creating a matrix in the interim?
Overview
Quick refresher for columnar transpositi... |
I'm in the middle of developing a video store rental application for a school project but am starting to question whether I'm going about things in the correct manner. Although the application is producing the desired results, I have a suspicion there's a more efficient way of coding/designing it. Any suggestions on h... |
I've written 3 factories as a part of a sign up process in AngularJS and Firebase. After completing them, I thought to myself, would any of these fit better as a service instead of a factory? From my research it's a bit fuzzy when it comes to choosing whether to create a service or a factory. If so, why would they fit ... |
I have written a program which calculates the sum of all the left nodes and the sum of right nodes in a Binary search tree.
I have used BFS to traverse the tree. The code is as follows:
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class SumLeftRightNod... |
I'm having some questions on creating a design for simple approval workflow. Some arbitrary thing (ItemToApprove) needs approval process. Approval process begins with creating ApprovalRoute which contains several approval steps (ApprovalStep). ItemToApprove goes sequentially through all steps until gets status Approved... |
This is a problem from topcoder tutorials
Given a list of N coins, their values (V1, V2, ... , VN), and the total sum S. Find the minimum number of coins the sum of which is S (we can use as many coins of one type as we want), or report that it's not possible to select coins in such a way that they sum up to S.
This... |
I have been trying recently to develop a code finding the next palindrome from a certain number. For example, if the input is 800, the output should be 808, as 808 being the next palindrome from 800.
Here's my code. It's fully functional, but on my online judge I get a problem with the time of the execution. My method ... |
I have a list of key value pairs, that is used as an intermediate store for building URL parameters or JSON data. Currently this is done with a linked list:
struct _kvp {
char *key;
struct _v *value; /* the implementation of _v does not matter right now */
unsigned char is_array;
struct _kvp *next;
};
... |
I have to write a program that solves a NxN Magic Square, with digits from 1 to N².
What do you think?
#include <iostream>
#include <fstream>
#include <string.h>
const int N = 3;
const int Possibili_N = N*N;
const int Magic_Constant = (N*((N*N)+1))/2;
using namespace std;
class MagicSquare{
bool Num_Possibili[Po... |
This a solution Luhn algorithm for credit validation.
This algorithm is a basic one inspired by wikipedia. I mean no check for length, type, and so on. You can enhance the base code as you want it to be.
The listing code of the following fucntion is tested on MSSQL 2012:
IF OBJECT_ID('dbo.LuhnALGValidation') IS NOT NUL... |
I wrote a script for Python 2.78 which is supposed to download and save a file from a given URL using the requests library.
In case that a connection to the server can be established and a valid response is received, the response (e.g. a HTML file) should be downloaded to hard disk.
If the server gives a bad HTTP respo... |
A while ago I started solving Binary Puzzles (also known as "binero"). Not having done much C++ in my life, although it feels like I have a pretty good understanding of C++ in general, I figured it was time to do some C++!
The rules for a Binary Puzzle are:
The entire grid should be filled up with 1's and 0's.
There c... |
My main questions: FileWithSave handles its saving itself, but delegates it to a repository object. This allows implementation details to be available without being present in the API when saving (transpose this to a Mail sending API as well, available for send but not public). Is this OK in terms of OOP practices? ... |
I'm implementing a dirpath and fdirpath functions, which allow to retrieve path from the directory handle (or its descriptor). This can be useful e.g. if one needs to implement some functions like openat(3) on systems which lack similar functions, but have fork(3), mmap(3) and pthreads. I'd like to know your opinions, ... |
I am trying to reverse the lines of a file by reading the file through an array.
Is there a more efficient and quicker way of achieving this?
import java.util.Scanner;
import java.io.*;
class ReverseNumbers {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("numb... |
Are there any optimization suggestions?
<?php
# Pascal's Triangle using Recursion.
$rows_to_generate = 15; // Define number of rows you want to generate.
$storage = array();
function get_elem($row,$pos) // generate element having number of row and number of position.
{
global $storage;
if(isset($storage[$ro... |
I have written AI for Tic-Tac-Toe using Negamax in JavaScript. The Negamax object is translated from an implementation written in Python. The code runs on a Node.js server and the player interacts with it via web socket. The code works and the game is unbeatable meaning it always wins if it can and if it can't, will fo... |
At my job, often I have to manually convert *.csv Files structured like:
number,number\n
number,number\n
number,number\n
...
To a regular *.txt file with the structure:
#1
double filename(number of columns, number of columns)
number number
number number
number number
...
This file is an input to another program,... |
I would like to know if the solution I came up with for managing relationships between entities is sensible. Guys in my team feel it is transparent, but maybe I'm missing a pitfall somewhere?
Consider the following situation:
@Entity
public class User {
@OneToMany(mappedBy = "user", cascade = ALL, orphanRemoval = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.