instruction stringlengths 71 71.9k |
|---|
I've started to learn very interesting concept of DI, IoC and related stuff.
I have decided to learn it using simple application, very tiny calculator (only basic functions: add, subtract, multiply & divide), because it's very conveniently to learn any new stuff with elementary application.
My question relates to the d... |
I am writing a very simple Prolog intepreter in Haskell. It's a class assignment and I really want to do it right.
I was able to (quite quickly) write a parser for the language. Today I borrowed a copy of Programming in Haskell by Graham Hutton and I decided I would rewrite my code to a more function-oriented style, us... |
I'm currently using a make shift INSERT on DUPLICATE UPDATE function that relies on a DB raw query from eloquent. I'm looking to improve the quality of the code and the speed. Please take a look
function bulkInsertBookTable($data)
{
$inserts = [];
foreach ($data as $item) {
$inserts[] = implode(', ', ['... |
I'm writing a simple Android app with a database and am trying to make the right architecture for accessing a database.
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setC... |
I'm trying to get a little more comfortable with using classes as they're meant to be used, instead of using them to decorate my code to make it look more legitimate. Can you see anything glaringly wrong/could be improved/possibly different implementations?
import random
class Player(object):
def __init__(self,pl... |
As a project I have written a graphics library for educational use to allow kids at my high school to make Java games without directly dealing with to the Java graphics API. I'm in the final stages, tweaking mainly for performance and readability, and I would like some input on how I handle transformations.
The idea of... |
This script counts how many matches were won by the team with a first half, second half, and full game time of possession differential advantage.
The data is stored in a pandas data frame:
Points H1 H2 Total
0 36 46 50 96
1 -5 16 18 34
2 47 12 65 77
3 12 79 13 92
4 ... |
I'm trying to practice and learn design patterns, and I decided to create a weather app using the revealing module pattern. How can I improve on this, and what mistakes did I make?
Main.js
import '../styles/main.scss';
import {weatherModule} from './weather';
import {dateModule} from './date';
dateModule.getCurrentDa... |
I frequently want to filter and select elements from a long (10,000s to millions of elements) vector in R. Often, this vector is a column in a data.frame. I am usually interested in rows of the vector that "match" any one of a separate list of 10 to 100 query values. However, since these are experimental data (mass ... |
I'm trying to smooth the movement of a cursor which has a set acceleration and max speed. I wrote this function to calculate the stopping distance of an object given its speed and acceleration, and it works, but it seems a little ridiculous.
function getStoppingDist(speed, accel) {
var dist = 0;
while (speed > 0)... |
Following Nadeem Afana's article about how to include internationalization into an MVC application, I have introduced i18n into one of my MVC applications.
These are my goals:
Use strongly typed resources
Allow to easily change existing resources strings without application redeployment (i.e. at runtime)
Easy to use... |
Write a Compress class defines two static methods, gzipFile(), which
compresses a file using GZIP compression format, and zipDirectory(),
which compresses the files (but not directories) in a directory using
the ZIP archive and compression format. gzipFile() uses the
GZIPOutputStream class, while zipDirectory(... |
I think this code is not optimized:
function changeSalesStage(value){
var $form = $( getProductsForm() );
if( typeof(value) == 'undefined' ) value = $("#sales_stage", $form).val();
// Failure
var cause = $("#causes_failure", $form);
var notes = $("#failure_notes", $form);
var seconder = $("#s... |
I need to check that a user is allowed to save/retrieve contacts to/from the database by calling a web service, and return an HTTP403 with an explanation if it is not the case.
So for the sake of factorizing the code, I decided to use a boolean method that "never" returns false and is there only to check this, and thro... |
I'm working on the following DP which finds the optimal way to allocate a resource. At each time step I can either allocate (0.2 resources) at cost C or not in which case the storage is reduced by the demand. The cost C depends on which time step I do the allocation.
I need to add quite a few more complex features, but... |
I wrote a Python 2.7 script, which plays tracks from the SoundCloud Top 50.
import atexit
import os
import shutil
import subprocess
import requests
if not os.path.exists('.tmp'):
os.mkdir('.tmp')
@atexit.register
def cleanup():
shutil.rmtree('.tmp')
class soundcloud_top50_player:
def __init__(self):
... |
Currently, I'm working on a project where I needed to run some code every time the page is hidden.
I searched high and low and found this question: Is there a way to detect if a browser window is not currently active?. The accepted answer did an amazing job, but it only sets a class, doesn't run a function.
So, with th... |
I'm writing a project, and the part I'm doing now is getting bloated real fast. How can I remove this nested if statements, but still have the same behaviour?
It would be nice the the resulting code was succinct, and extra local flags weren't required. This might not look so bad now, but I'm planning on writing more me... |
I'm creating a dictionary app using Win32 API. I stored the word meaning in a file called dictionary.dic in the following format:
Word Meaning
A The first letter
B The second letter
... and so on
As my window is created, I load the dictionary file into the std::map object using this code:
std::map<wstring, w... |
I'm new with JavaScript and need your advice. The idea is to show/hide text field depending on select option. I have a working code, but I believe it could be more readable and better. What have I missed?
<script type="text/javascript">
<!--
function showHide(){
var selectedValue =document.getElementById... |
I am making a data drive system for creatures, abilities, items, etc. Considering my ability objects I need to create "templates" from the these since parsing them in real time is too slow. I am trying to find a way to just reference these on my creatures instead of a copy of the reference for each ability.
The thing i... |
Problem description
Given a text \$T[0..n)\$, a pattern \$P[0..m)\$, and a nonnegative
integer \$k\$, report all positions \$j \in [0..n)\$ such that \$ed(P,
T(j - l..j]) \leq k\$ for some \$l \geq 0\$, where \$ed\$ is the
Levenshtein distance between two input strings.
Question
I am comparing two algorithms: the trivi... |
I have written a Java class that parses Shoutcast 2 stats XML. It uses JDOM to parse the XML. I have only basic knowledge of Java and I wrote this class in about 3 hours. It works, but I don't know if I've done everything right, or how efficient it is. I intend to use this class in an Android app I am working on. You c... |
I have written a program to read HTML file, find particular text, write text from that particular text to next particular text in a newly opened file. I am interested in code review. I am very new PHP.
<?php
$FILE = "testing.html";
$count = 0;
$directoryName = explode('.',$FILE)[0];
$TAG = "/x-berschrift-1--nur-f-r-He... |
This is from the Resin codebase. It is fast at lookup but I could use some help making it faster at buildup. Loaded with 210K words, it looks up pretty much any node and its descendants in zero time. Buildup takes 3000 ms.
using System;
using System.Collections.Generic;
using System.IO;
namespace Resin
{
public cl... |
I've been trying to learn Python for a bit now. I've taken a few courses, but I've found that I've been going about them wrong and had allowed them to "hold my hand" too much. I'm trying to build projects on my own and thought I would start off small. My third or so project was this Pig Latin translator and I wanted to... |
I want to get the first argument as a number, if there is any. This does not feel quite right, but I don't know yet what the Rust way would be.
I'm not searching for a args-framework or something, I just want to get a grip on doing stuff with Rust.
fn limit_from_args(args: env::Args) -> i32 {
let args: Vec<String> ... |
A sorted array [0,1,2,3,4,5] when rotated n times (3 times in this case) becomes [3,4,5,0,1,2], meaning elements in the front move to the end. The code below finds the minimum element in this array, which is the pivot point of rotation.
function findminimum(a, start, end){
if(start>end || start == end || a[start]<... |
This is a follow up to this post I uploaded a few days back on my alternative account about a circular buffer in C. I'm confident that I fixed most of the warnings and even added an iterator.
circularBuffer.h
#ifndef CIRCULAR_BUFFER_H
#define CIRCULAR_BUFFER_H
#include <stddef.h> // max_align_t in source
struct cir... |
I am working on an iOS project and I'm in charge of testing most parts of it. As I write some tests, I often have the need to wait for an asynchronous method to finish, and then test that something did not happen.
For example, try to login with an invalid username and password, wait until the network communications are... |
This is code that handles pushing data to an analytics API, and IMO it feels too much like Java.
logActivity is a method that uses Dispatch to POST the data to this API. I am worried that an exception could occur and that is why I wrapped the methods in a try/catch block. However, this feels very Javaesque.
Do I even n... |
This was an experiment to take any text and wrap it to a given number of columns. It also wraps
the text in just one box, lets you box multiple blocks of text, and also lets you limit the number
of boxes per line. The main paragraph tested was one that I found on Yahoo that I thought was
really fun to use as a test. Wo... |
I'm a novice regarding both C++ and Qt. This class is used in my project to get an image from a web service.
If a new call to StartDownload is made before the previous has finished, the old one can safely be discarded as it won't be needed any more. This is because a new request is made for each resize event, as one of... |
I want to write a class that returns a Stream of permutations of an int[].
public class Permutations {
public static Stream<int[]> of(int[] array) {
return permute(array, array.length);
}
public static Stream<int[]> permute(int[] array, int n) {
if (n == 1) {
return Stream.of(Arr... |
I had a task to create a program to simulate a simple card game.
Given an input file with number of players, the players and finally a list of cards played, I had to change the game state accordingly (I believe card-action relations are clear enough from the code, so I won't go into detail here).
The task was not inten... |
Consider a 3x3 square surrounding a cell (marked @) on a grid:
0 1 1
1 @ 0
1 1 1
I need to find the number of groups of open cells (ones) surrounding the center cell. In the above example, there are two groups of open cells. All cells have the value 0, closed, or 1, open.
Here's what I have:
{
// x and y coordinat... |
This script is very basic: it does one thing. Connect to it's root and it will log your IP if it has never seen it before. Connect to /logs, and it will show a list of unique IPs within the server storage. I can't take 100 percent credit for it. I grabbed it off of Stack Overflow, modified it to actually run on App Eng... |
I got inspired by Stack Overflow to build a simple state machine which can test if a sequence contains 0,1. I have two questions:
How can I get rid of line | _ -> (function `q0 -> `q0 | `q2 ->
`q2 | `q1 -> `q1)
How can I improve that code?
(If it is matters, I came from Python and many things in OCaml seem unusual to... |
So I have a file with a list of dates that are to be redirected as input to stdin and what the program does is it searches for valid dates, appends them to the output file and then appends all the dates in the input file to the output file. In other words, at the end of the program there would be a list of all the vali... |
This is literally the first time I've ever used JavaScript so I know it's really bad and how to improve it just not how to implement it. Basically, I need to loop through all the elements instead of manually checking and updating each one. Any suggestions on how to do that, and other recommendations?
<!-- Kalenpw -->... |
I created a function to add and return the average rating.
Rating Function
// Adding AddRating
final function AddRating($rt_target_id, $u_id, $rt_vote,$moduleName){
$error = 0;
if(!empty($moduleName) && $rt_target_id != 0 && $u_id != 0){
$tableName = '';
switch ($moduleNam... |
I created event delegation like concept which is present in jQuery. AFAIK, event delegation is used to register an event for an element which is supposed to be added dynamically. So, in jQuery we do the following:
$(document.body)
.on('click', '.main', function(){ /* code here */ });
.on('click', 'div.main', fu... |
(See the next iteration.)
I have subclassed java.util.ArrayList in order to be able to "rotate" it in constant time simply by moving a finger index. See what I have:
RotableList.java
package net.coderodde.util;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
i... |
One of my university assignments asked us to create a program using struct in order to create a simple event scheduler. This program is for a single day only, not multiple days.
Sample Input / Output
For a few reasons, I've opted to create a .GIF to display the sample input / output:
An example save file:
8 30 denti... |
Problem (Rephrased from here):
The radical of \$n\$, \$rad(n)\$, is the product of distinct prime factors of \$n\$. For example, \$504 = 2^3 × 3^2 × 7\$, so \$rad(504) = 2 × 3 × 7 = 42\$.
We shall define the triplet of positive integers \$(a, b, c)\$ to be an abc-hit if:
\$GCD(a, b) = GCD(a, c) = GCD(b, c) = 1\$
\$... |
I've created this 3D vector class and would like it to be reviewed. I wonder if there are still some improvements that can be made. This is a header only implementation.
#pragma once
#include <string>
template<class T> class vec3
{
public:
union {
T f[3];
struct {
T x, y, z;
... |
I have started learning Java recently and was looking into the challenges on sorting on Hackerrank.I solved the following problemHackerrank on Insertion Sort.
The challenge was :
In Insertion Sort Part 1, you sorted one element into an array. Using the same approach repeatedly, can you sort an entire unsorted array?
G... |
I have a situation, where I want to add many classes as instance variables of another class, plus perform some action on each class. The purpose is to have an 'app' with many 'views', to represent PageObjects.For instance:
class App
attr_reader :login_view, :list_view, :create_view
def initialize
action([Login... |
First time I write the tests before the actual code.
All fit in the same module.
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from os.path import join as path_join
from xmlrpclib import Fault, ServerProxy
XMLRPC_URL = 'xmlrpc/2'
class Model(object):
def __init__(self, host, db, uid, pwd, model):
sel... |
I have just decided to get into programming as a hobby (and possibly a job in the distant future). After learning the basics of Python, I made Tic-Tac-Toe to apply what I've learned. I would appreciate any and all feedback on my code and the way I set up the logic of the game. I would like to avoid picking up bad co... |
I was wondering if you can help me out. I wanted to know if there is an easier way to do the following. My code works but I feel like there is a lot things going out with multiple loops and wanted to see if anyone can help me condense the code i have attached to make it clear.
In my code I have created 3 subroutines (i... |
The getDynamicTeacherCount function is generating number-based reports from the table that I have in database and the getDynamicPercentage function generates percentage for these reports; then I am calling the getReports function from the related controller and pass the getReport returned array to the Laravel View and ... |
This include was written for a Jekyll site I'm building. It generates nested HTML unordered lists to a given depth dynamically by parsing page urls. It works fine, but the code feels messy and it takes Jekyll upwards of 20 seconds to build the site (up from ~3 seconds before this navigation was implemented).
Basically ... |
I'm not used to Python.
The script opens serial communications with an Arduino unit and send commands to and receives information from the Arduino. It is intended to run indefinitely until the system is shut down or pulled out of field deployment/laboratory testing.
The time.sleep() calls with offsets are assurances th... |
I'm a C++ newbie and so far have written my code mostly in an not OO way. Since this is getting confusing I'd like to start creating libraries for some of the functionalities that I've implemented. The following program basically issues callback functions depending on a counter. It's made to detect the duration of a bu... |
In Service.Insert(), I call DeviceRepo.Insert() and in Service.Update(), I call DeviceRepo.Update(). All my other code is exactly the same.
I'm thinking I can make one method that do the same thing update. I want to update and insert when I will insert a device.
The methods respectively insert a new or update an existi... |
I am using CTR mode (it is a cipher in itself) in this code. I just wanted to see what you thought about it before I finish it.
(Yes, I know that the plaintext length and key length must be highly specific. I will take care of that with padding later.)
I just wanted to know if you thought if this code was cryptographic... |
Within my app i have a UIButton (avatar button which shows a profileVC) within a UICollectionView this button shows up in about 4-5 other views. I'm currently adding the target within cellForItemAtIndexPath in each view controller and pushing the view from a public function pushNewViews. I was wondering if they was a b... |
I have this Excel macro I created to highlight all instances of a number if at least one instance is already highlighted before running the macro.
Sub highlightXIDs()
Dim prods As Object: Set prods = CreateObject("Scripting.Dictionary")
Dim lastRow As Long: lastRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp... |
I have this Java class for producing rotations of an input string:
StringRotator.java
package net.coderodde.util;
import java.util.Objects;
/**
* This class implements a data type for rotating strings.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Mar 24, 2016)
*/
public class StringRotator {
/**
... |
This is my first time using semaphores and I was wondering if I implemented them to the best of their abilities in my code....
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include<semaphore.h>
#include <math.h>
#define NR_THREAD 2
int sum=0;
unsigned int seed;
sem... |
I have the following code that makes use of the DiskArbitration framework to mount a disk to its default location:
#import <CoreFoundation/CoreFoundation.h>
#import <DiskArbitration/DiskArbitration.h>
void MountCallback(DADiskRef disk, DADissenterRef dissenter, void *context);
int main(int argc, const char *argv[]) {... |
I have created a brainteaser, which I called the "impossible problem" (see this video I made). The aim is to create a valid 3-digit subtraction which uses every digit from 1 to 9 once. Here is an example of one of the solutions: 873-254=619.
After finding it hard to come up with answers I created this program. What it... |
Just wanted to get a bit of feedback on this simple cache. My use case is to store this data on an Android client to avoid making a high volume of network calls for lookups.
I feel like maybe I should just extend HashMap with the small amount I've added, or change up my thinking and do some type of static implementatio... |
I have created a pretty bad (just being honest) Golang library. I will take any and all advice, as long as it's helpful. Sorry it's so long. Also, I easily forget some things, so many functions in convert are just light wrappers around strconv, etc.
GitHub
Convert
package convert
import (
"github.com/retep-mathwiz... |
Could you guys please review the Graph Library I developed in C? It's also on GitHub
#include "graph.h"
/*Function:
* Graph_node_in_adjacency
*
* In this function we verify whether the node is
* present in adjacency List of a vertex
*
* Input:
* Graph_edges_t
* vertex_number_t
*
* Output:
* b... |
Over on Stack Overflow, someone asked a simple Haskell question: how to test whether there is exactly one distinct vowel in a given string. To clarify, there can be any number of non-vowel characters, and the vowel may be repeated any number of times (at least once!), but no other vowels may occur.
I proposed the below... |
How should one break this component down to better perform unit test on its behaviors?
Issues:
Authentication middleware component makes external request.
Must recognize preflight and final flight. (Exceptions)
Must verify path.
Only want to expose crossOriginRequest.
Please criticize anything you see wrong in logic... |
I'm learning C and decided to write my first major project in C. I was bored and wanted to play blackjack so I decided to create my own game. My program starts the user off with 500 credits and continues playing until the user runs out of credits or quits, at which point they can start again by typing play. The main in... |
I am using the following VBA code to replace accented letters with regular letters in a spreadsheet. This is necessary because these spreadsheets have to be uploaded to an import tool that does not allow foreign characters.
Function RemoveAccentsFromForeignLetters()
StartNewTask ("Removing accents from foreign let... |
I'm trying to figure out if there's a better way to run the code below.
Basically Course is an association of Student and courses_needed is an array of Course where I have many Students have and need many Courses and I'm trying to figure out the demand.
I've came up with the following code and it runs, which is fine, b... |
I'm making an image viewer and before I continue development I want to make sure I haven't done anything bad. In particular, I was wondering if my error handling is sane.
Most of the code is OpenGL/glfw boilerplate, so far all that happens is the creation of an OpenGL context and then I use stb_image to load the image ... |
In preparing this answer, one of the components was an algorithm to rearrange a sorted array in a particular way. To put it succinctly, here's the problem description:
Given an array \$A\$ with \$n\$ elements \$A = \{ A_1, A_2, A_3, \dots , A_{n-2}, A_{n-1}, A_{n} \}\$ rearrange the contents such that the resulting a... |
Today I coded a class to get settings from a file and to load them in to a dictionary.
Please post and feedback, improvements and changes, no matter how big or small, as long as they are actual improvement and not disadvantages.
using log4net;
using System;
using System.Collections.Generic;
using System.IO;
using Syste... |
I am coding an interview question from Yahoo Software Engineer Intern Interview.
Given an unordered list of numbers, find all pairs that add up to x.
I have a working solution in Java:
public static void main (String args[]){
int[] numbers = new int[]{2, 5, 7, 3, 9, 4, 1, 8}; //input array
int x =... |
I created an helper method to return a List of UIElements where the returned elements have to match with one of the Types which I pass to the method.
First I used this method to get all the children of one type:
public static IEnumerable<T> FindVisualChildren<T>(DependencyObject dependencyObj) where T : DependencyObj... |
I implemented a function for pager link creation, it looks like this:
function createPagerObject(pageUri, page, totPages) {
const MAX_PAGES_IN_PAGER = 6;
// for the first three pages the starting would be 1
let pageNumber = Math.sign(page - 3) > 0 ? page - 3 : 1;
let pager = [];
for(let i = 0; i <... |
I have this little function to validate e-mail. It's a little piece of code to search major mistakes in e-mail input and it's part of a bigger program I have to complete as a school assignment. Is there a better way to do it in C?
I'd like to do it in regex but if I have understood correctly, C under Windows doesn't ... |
(See the previous (and initial) iteration.)
Compared to the previous iteration, I have added more methods that maintain the invariant required for constant time rotations, such as bulk add/remove, iterators, dumping contents to array.
I have more progress on java.util.ArrayList subclass that supports rotations in const... |
Want to brush up my rusty web dev skills. I want to call the twitch API for several channels and eventually call a callback function when all results are in without using a sync call.
I didn't work with JavaScript for a long time, so I'm not sure if my solution is a good way, especially how I figure out if the callback... |
source : https://github.com/Zakisu/QB_Mysql/blob/master/mysql/Mysql.php
please review mycode
read the docs about the usage
<?php
/**
* Mysql Class
*
* @category Database Access
* @package Mysql
* @author Muhammad Zaki Sulistya <zaki.sulistya@gmail.com>
* @copyright Copyright (c) 2016
*/
class QB_Mysql
{
... |
Following task:
You've got an array which contains parts. Parts can contain subparts. Subparts can contain further subparts and so on.
For example:
computer
cpu
hardDisc
graphicsCard
graphicsCardCpu
graphicsCardRam
Let's suppose I have a correct structure where every part has a unique id. Su... |
I'm trying to find the shortest and best way to achieve the following:
Given input integer $N, get the following output:
n = 0, output = 0
n = 1, output = 0
n = 2, output = 10
n = 3, output = 100
n = 4, output = 1000
n = 5, output = 10000
I do this with the following code, but there must be a better option to do... |
What is a cleaner and/or clearer way of writing the following method
def disbursements
@invoice = Invoice.find(params[:id])
utc_time = Time.parse.now.utc
#check if invoice_id is not nil
if @invoice.invoice_id == nil
@invoice.errors[:invoice_id] << "invoice_id can not be blank"
end
#check if trip date is no... |
I am a Laravel newbie so please forgive me for my code... I have a method, in a Laravel controller, that updates the current logged user profile (postProfileGeneral()).
Logged user can upload a profile picture, and I manipulate the uploaded file (i.e. remove spaces, create unique name, etc.); since I'd like to reuse th... |
I've never been into web a lot, but I really want to.
I started from simple things. I have some experience in .NET and c#.
But the world of javascript is completely new for me.
I wrote simple calculator just to try js.
Maybe there are some ridiculous things in my code that I want to know.
I'm not really interested... |
This is my first SFML game. There are 2 players: the red circle and the yellow circle. The red circle is controlled by Up,down,left and right keys, the yellow one is controlled by WASD keys. The players are supposed to keep on trying to get behind each other in order to move them and get them inside the black circle, t... |
This is a class similar to std::pair and std::tuple inspired by Alexandresku's Expected<T>. Let me know if this class can be helpful for simple error handling.
template<class E, class T>
class CheckValue{
public:
template<class UT>
CheckValue(const E &e, UT &&t) : e(e), t(std::forward<UT>(t)){}
operator E(... |
I am building an iOS SDK to be consumed by apps. I am building an object that represents a physical place. The interface looks like so:
@interface RDPlace : NSObject
@property (nonatomic, strong, readonly) NSString *city;
@property (nonatomic, strong, readonly) NSString *country;
@property (nonatomic, strong, readon... |
I know there is a balance to be struck between writing dry code and damp code but I have the feeling that this is a bit too repeative. Is there a terse yet self explainatory way to rewrite these tests?
class TripTest < ActiveSupport::TestCase
def setup
@trip = trips(:one)
@invoice = invoices(:one)
end
t... |
Working codepen: http://codepen.io/leongaban/pen/oxwLzE?editors=1010
The function below takes in user entered text through the cli: V=patch gulp build
It then checks for the last version of the build folder, then iterates the appropriate version number.
Hoping to condense all the if/else into more functional code.
last... |
I am new to AngularJS and I thought of trying something simple: a notification factory that is useful for displaying actions alert messages like "Save successfully!" or "Validation errors: ...".
The factory - first thing I have tried is to define a container to hold all UI element data and use it for binding. Basically... |
I thought about using a macro to auto close FILE pointers at the end of a block. My solution so far is:
FILE *fopen_safe(const char *filename, const char *mode) {
FILE *fp = fopen(filename, mode);
if (!fp) {
perror("fopen");
exit(EXIT_FAILURE);
}
return fp;
}
#define with_fopen(fp, fi... |
I'm interested in receiving some feedback regarding an Event system that I wrote. Both in style and implementation, but also in overall design and the design decisions that I made.
It is intended to be used as part of a game (hobby project of mine) and is intended to be used on a single thread. While receivers will alw... |
This is a working linked list that will be used as a vector. Instead of using dynamic arrays, I am using a linked list. I would like to see a more concise solution without utilizing the STL.
SimpleVector.h
class SimpleVector
{
public:
SimpleVector(){
head = nullptr;
}
SimpleVector(const SimpleVect... |
This is my second SFML game, which is Pong. Please tell me what you think.
#include <iostream>
#include <SFML/Graphics.hpp>
int player1score = 0;
int player2score = 0;
bool intersects(sf::CircleShape& c1, sf::RectangleShape& rect2){
sf::FloatRect circle = c1.getGlobalBounds();
sf::FloatRect rectangle = rect2.getGlob... |
I implemented the DFS and BFS. Please offer improvements.
#!/usr/bin/python
# coding=utf-8
# Para poder poner acentos en comentarios
# Alberto Penhos
# A01018426
#
# Se hizo con listas, ahí se guardan los valores en el siguiente formato:
# Posición de la lista:
# 0 3 6
# 1 4 7
# 2 5 8
#
# La meta es el estado... |
Continuing on my VB.NET quest, I came across this slightly more challenging problem.
You are given a 2D matrix, a, of dimension \$M\$x\$N\$ and a positive
integer \$R\$. You have to rotate the matrix \$R\$ times and print the
resultant matrix. Rotation should be in anti-clockwise direction.
Rotation of a 4x5 matri... |
I implemented a fixed-length stack in Java for use in my fractal generator program, an RPN calculator and my esolang interpreter. This is a generic stack, and goes over and above the call of duty in places to supply my esolang interpreter with some essential methods (the initStack(),dumpStack() and ...N() methods, as w... |
I started a project the other day and started going down the path of using async and await as I have never used it before and it seems like a good match. The app that I'm making is a WPF solution using MVVM. It is going to read from a smart card and show the information that was saved to the card. It is part of a demo/... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.