instruction_seed stringlengths 71 95.1k | _source stringclasses 1
value |
|---|---|
I'm learning the mvc pattern and today I finished my first mvc routing class.
Hope you can give me some tipps and improvements.
Router.php
<?php
namespace System\Libraries;
class Router
{
/**
* Store the given parameters
*
* @var array
*/
private $_param = [];
/**
* Default actio... | stackexchange/codereview |
Is this an efficient way of finding the minimum using binary search?
//Find the minimum in a sorted rotated list of numbers
function findmin(arr, low, high){
if(low==high)
return arr[low];
if(arr[low]<arr[high])
return arr[low];
if((high-low) == 1)
return Math.min(arr[high], arr[low]);
var mid = M... | stackexchange/codereview |
I have REST API written on laravel and front end on vue.js. It is a dashboard for an ecommerce store where you can connect to post shipment service API to upload order shipment data and get tracking number (with .png label). So after I receive tracking number label from post service API I need possibility to show it in... | stackexchange/codereview |
I want to randomly permute a finite list in the most effective and efficient way in C#. My attempt is as follows.
/*===================================*
* Compile it to produce Shuffle.exe *
* ==================================*/
using System;
using System.Collections.Generic;
using System.IO;
namespace Shuffle
{
... | stackexchange/codereview |
I was curious on what, if anything, I could be doing better. I have been spending the last few days working with Java and learning some basics and wanted to try this challenge and making it two classes. I found the scanner is sometimes strange and doesn't take input the first time.
import java.util.Scanner;
import java... | stackexchange/codereview |
I'm implementing a password hashing method for a website. The code below is part of the User class.
Any pointers on what I could do better?
private string GenerateSalt(int SaltLength) {
using (var rng = new RNGCryptoServiceProvider()) {
var salt_bytes = new byte[SaltLength];
rng.GetNonZeroBytes(salt... | stackexchange/codereview |
I met the RESTful ideology and I fell in love with it. However the only request methods supported by HTML forms so far are GET and POST, which is kind of sad, because this means that to use REST as it's supposed to be used I need to use some work around which is likely to not be pretty, as it really is.
So the only way... | stackexchange/codereview |
Here is the problem: some script is injecting some HTML5 elements (actually a button with the #thebutton ID) to the current DOM.
But this is a third party script and I have no control of when this will be injected to the page.
I need to click automatically on this button when the button is injected to the DOM. Here is... | stackexchange/codereview |
Given a dictionary where the values are iterables, print the dictionary sorted by the length of its values.
def sort_dict_by_value_len(lst):
while lst:
min_key = min([(len(v), k) for (k, v) in lst.items()])
print(min_key[1], lst.pop(min_key[1]))
sort_dict_by_value_len({1: 'one', 2: 'two', 3: 'three... | stackexchange/codereview |
ES6 syntax helps to write code in a declarative style, which is exactly what I am trying to achieve here. Any advice to make my code "more declarative" (and easier to read) is welcomed.
const middleIndex = xs => Math.floor(xs.length / 2);
const split = xs => {
return {
fst: xs.slice(0, middleIndex(xs)),
... | stackexchange/codereview |
The function findMinimal() receives a tuple from a list which contains 171 tuples, each of them go into the function one by one and, for each tuple, it searches the best pair via minimalTscore out of those that match by industry (approx. 20 names, for each one). How can I make the function to run faster? At the moment,... | stackexchange/codereview |
This is the Swift code from one of the view controllers in my app that calculates a one rep maximum weight a person can theoretically lift. This particular view controller presents a list in a tableView of all types of lifts a user can choose from to set as a default preference. When the user selects a lift name, the r... | stackexchange/codereview |
I am working on an application in C# WPF which reads a large file containing a number of HL7 formatted reports. My application takes in the file, reads and extracts any lines that starts with OBX and stores it into a List. It then tries to extract report headers from the each line, if one exists, based on a handle-full... | stackexchange/codereview |
I need to go and rework a bunch of notation in a large body of work. But I might change my mind later, so I want to move to defining the notation a bit more semantically (e.g. writing \v x to represent a vector, so I can later decide to format vectors in different ways).
On thing that is currently wrong with it is that... | stackexchange/codereview |
I made what started out as a web browser but now is a scanner for open ports. I wanted to know if you think this is a realistic or a unreliable tool for port testing. I found some open ports on my computer and was able to send data through them.
#include <windows.h>
#include <winsock2.h>
#include <conio.h>
#include <st... | stackexchange/codereview |
I was thinking of building a really flexible fluent API for my persistence layer. One of my goals is to achieve somehow the following result:
IEnumerable<User> users = _userRepo.Use(users => users.Create(new User("MattDamon"),
new User("GeorgeClooney"),
... | stackexchange/codereview |
I am writing a bunch of Math related classes:BigInteger,Fraction,matrix,vector,polynomial,set etc.All of these classes will use each other.The classes will either work in decimal format or in Rational format at a time(eg as FractionalMatrix and DecimalMatrix) so I thought it will be best to implement the Fraction class... | stackexchange/codereview |
I wrote this script for a code challenge on TreeHouse. I already submitted my code, but I am looking for an after the fact feedback.
The challenge was to open a file of text, remove specific words (provided in another file) and do the following:
Output to the screen in a readable fashion
1. total word count after fi... | stackexchange/codereview |
Trying to create something really lightweight. Sources are on GitHub.
To create a proxy we need to define an interface first, e.g.:
// Fake Online REST API for Testing and Prototyping
[Site("https://jsonplaceholder.typicode.com")]
public interface ITypicode
{
[Get("posts")]
Task<BlogPost[]> GetAsync();
... | stackexchange/codereview |
The following code is a controller spec used in a Rails 4.2 application with RSpec 3.5. I would greatly appreciate your suggestions on how to improve it (e.g., efficiency, readability, maintainability, DRYness).
# spec/controllers/authors_controller_spec.rb
require "rails_helper"
RSpec.describe AuthorsController, :foc... | stackexchange/codereview |
I'm developing a PHP function for calculating labor percentage (labor cost/sales) accounting for daily and weekly overtime rules, if applicable, based on the payroll period; the wages for each employee in the time input search range are calculated then summed to determine total labor cost.
The function takes start/end ... | stackexchange/codereview |
Background
I am more formally trained in backend/server-side coding. Over my career I have often found myself thrown into front-end coding. I have spent the last year and a half learning JavaScript/CSS3 on an "on Demand" basis. I feel like I am getting the hang of it, doing fancier things to meet UX requirements like a... | stackexchange/codereview |
I'd like to get a little feedback on this async socket wrapper. My goal is to merge socket Begin/End methods into a single async call. I also wanted to wrap exceptions so they are easier to handle in others areas of my program. Any red flags? Any potential problems? I know its not doing much but I want to get this righ... | stackexchange/codereview |
I've made a simple drawer using CSS3 and jQuery that works with hover and click. It seems to be working fine but surely there's a simpler way of writing the code.
Fiddle: http://jsfiddle.net/73MpU/
$("#bottom-page").click(function () {
$("#top-page").addClass("push");
});
$("#bottom-page").mouseover(function () {
... | stackexchange/codereview |
I wrote some code to encrypt and decrypt some user credentials for services that a locally run application needs to work.
I get a password from the user, use it to stretch a key via Scrypt, and then use the key to do authenticated symmetric encryption with ChaChaPoly1305.
I use the hostname as salt for the key, so that... | stackexchange/codereview |
I have some custom tables in a Wordpress database that I need to export to CSV. I created a dashboard widget to help with this based on some assistance given to me on on one of my SO questions. It basically consists of a single button that posts back and does some output buffering to render the CSV.
I've had it working... | stackexchange/codereview |
I am working on a C# MVC website. in which i am using tabs.I was trying to stay on the current tab when page refreshes.
I achieved this by following code:
$(document).ready(function () {
if (window.location.href.indexOf("?") > -1) {
var newURL = location.href;
window.history.pushState('object', docu... | stackexchange/codereview |
I have to format numbers that are either whole numbers or mixed fractional numbers with quarters (1/4, 1/2, 3/4) or thirds (1/3, 2/3).
The numbers are given as floats, for example 1.3333333 or 1.5 and are therefore inaccurate (but always close to a quarter or a third).
The formatting method is supposed to return Unicod... | stackexchange/codereview |
This will test if a user entered an pangram (every letter in alphabet used at least once), however with 4 for loops there's got to be a better algorithmic approach or with the language of C itself.
pangram.c
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
typedef enum { true, false }... | stackexchange/codereview |
I am still learning the javascript language.
Recently I've written simple code for a task list. I am searching for improvements and advice from more experienced users. Are there any improvements, changes or specific patterns for this task?
PS- I wanted to use pure JavaScript (e.g. no jQuery or AngularJS) as this is on... | stackexchange/codereview |
I've used the typical INT array sort function found all over the internet for years, but I've also had a need to sort other items in an array, or even to just simple take an Array of multiple types of items and get it in order for later readability. Thus leading me to the smartSort method I list below. If I've anything... | stackexchange/codereview |
This function computes and returns the number of divisors an integer has. But it is very slow and I believe it can be optimized for speed.
unsigned long long int find_no_of_divisors(unsigned long long int myno,FILE *ifp)
{
unsigned long long int divsrs = 2;
unsigned long long int k = 2;
if(myno == 1)... | stackexchange/codereview |
Each day I receive files from different customers relaying the same information, but the customers use proprietary formats. For example,
Customer1Data = {'User':['BobJones','BobJones','BobJones'],
'UserSong':['Song1','Song2','Song3'],
'UserSplit':[0.50,0.25,0.50],
'UserEarnings':[100,200,300]}
Customer2Data = {'Name':... | stackexchange/codereview |
I have a message coming in and I need to match it against the expected messages. The program will eventually do something as a result of receiving those messages. I am not very experienced at programming, but surely there should be a better way to declare all those messages it can be in like a separate entity and then ... | stackexchange/codereview |
After doing the Cryptopals challanges, which I found scrolling through codereview, and finally being able to solve set1 challenge 6. I decided to have a little xor fun, and make an automated xor encryptor/decryptor.
Usage is pretty straightforward
You can encrypt from a file to another file
Or try to decrypt from a fi... | stackexchange/codereview |
Could you please advise on the code and its design? Is there any way I can apply object oriented principles to make the design robust yet flexible?
public class RouteFinder{
/** Used to compute shortest distance from source station to all other station in a given network.
* @param source source station from w... | stackexchange/codereview |
I want to be able to improve the way I am sending these emails because it is currently not testable (via Mocking) and it is hard to maintain.
Main Sender (I also need an Async method on there but I have left it out):
public class MailSender
{
protected bool SendEmail(MailAddress toAddress, string subject, string bo... | stackexchange/codereview |
I've just created a simple VAT calculator. The script works fine though some animations seem a little buggy. Being a javascript beginner I'd like to ask more experienced programmers their opinion about my code. Do you have any helpful criticism to make my code more performant?
document.addEventListener('DOMContentLoa... | stackexchange/codereview |
I would like to ask your comments on my contest code for the following problem:
We're going to have a slightly more logical puzzle today. We're going to write a program that will find a path through a simple maze.
Formal Inputs & Outputs
Input Description
Through standard console,
you will be given two numbers X and... | stackexchange/codereview |
I have a database-intensive app, almost every activity requires access to the database, both reading and writing.
I had a lot of problems with separate threads and activities on the stack closing connections to the database when the current activity was using it, even if I opened and closed the database immediately bef... | stackexchange/codereview |
I'm teaching myself Python.
I wrote this code for work to help me troubleshoot end users PCs. It opens a GUI with a selection of buttons. It's written in python using pyinstaller to convert it to an executable. It's super slow - taking 10-15+ seconds to run on a PC. Why is it so slow and how can I improve it overall?
T... | stackexchange/codereview |
I have created a simple Javascript game and want some second opinions on the code. How can it be done more efficiently for example?
Please see the code below, plus a link to a live working version on github.
Code to github
Thanks in advance.
(function(){
// The intro element. This element displays some introductory ... | stackexchange/codereview |
I've written the following code:
{- ...
...
... -}
data Ellipsoid
data Halfplane
data Intersection
data PointSet s a where
Halfplane :: RealFrac a =>
a -> a -> a -> (a -> a -> Bool) -> a ->
PointSet Halfplane a
Ellipsoid :: RealFrac a =>
a -> a -> a -> ... | stackexchange/codereview |
I'm in the process of learning Scala, and started working through a series of coding puzzles that I've done previously in other languages.
For example, this solution, coded in Erlang:
sum_multiples(Max, Max, Acc) -> io:format("The sum of all the multiples of 3 or 5 below ~p: ~p~n", [Max, Acc]);
sum_multiples(Current, ... | stackexchange/codereview |
I've been working on a game somewhat similar to this one for a little while now. My game is based around a 'board,' which is filled with different types of particles that react with one another and the environment. With every update of the screen, the board, and all of the particles within it have to be updated (moving... | stackexchange/codereview |
I wanted to cache methods using unity interception and not have the parameters passed in stay alive for the sake of caching. If the objects would have gone out of scope without caching then the cache should be invalidated. Also wanted to use MemoryCache class as if memory is low the cache should be the first thing to... | stackexchange/codereview |
Given a heap of pixel data, and a width and height associated with that pixel data, I've written code which will save that data as an image, and it more-or-less works as expected.
//I'm using the FreeImage library.
#include<freeimage.h>
/*Some other, irrelevant code*/
namespace filesystem = std::experimental::filesys... | stackexchange/codereview |
I'm trying to solve this question:
Given a positive integral number n, return a strictly increasing
sequence (list/array/string depending on the language) of numbers, so
that the sum of the squares is equal to n².
If there are multiple solutions (and there will be), return the result
with the largest possible va... | stackexchange/codereview |
I want to write read savefile function with smart pointers and SDL2. I have little expirience with smart pointers and just want to ask is my code good, correct and no memory leaks.
this is my code:
std::shared_ptr<SDL_RWops> saveFile;
--
int GameEngine::ReadSave() {
int Highlevel;
//Open file for rea... | stackexchange/codereview |
Here is my plunker example of what I am doing.
jQuery is a great way to use slide transitions and seem to work well with angular as long as you are only using the methods on the element object inside a directive.
Basically I am using a directive for divs I want to slide toggle which listens for a broadcast from the co... | stackexchange/codereview |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
typedef int STATUS;
#define ERROR -1
#define OKAY 0
struct version
{
unsigned char major;
unsigned char minor;
unsigned char build;
unsigned char patch;
};
STATUS is_less_than(struct version * original, struct version *com... | stackexchange/codereview |
I wanted to create a program that lists all prime numbers to a given upper bound and that will also provide the amount of primes in the set. After many hours of trial and error I was able to solve it.
I am sure this is not efficient and I want to learn how to look at code and see where improvements can be made. Or just... | stackexchange/codereview |
I implemented a CSV Parser with Separation of concerns and SOLID principles in mind.
Does that code match the principles?
Here a sample data (CSV):
Participant;Eagerness;Education;Stability;Total
"John Doe";6.4;"G";1.3;9.0
"John Smith";2.9;"X";1.5;;
Main file:
<?php
require __DIR__ . DIRECTORY_SEPARATOR . 'vendor' . ... | stackexchange/codereview |
I've written this very simple quiz program, I'm trying to get to grips with OOP (Object Orientated Programming), so I've started simple with very basic Classes. The nature of the code would have suited using functions but I wanted to practice with Python Classes.
Any comments or suggestions about my code would be most ... | stackexchange/codereview |
I've made a plug-in for Unity3d for iOS. The plug-in's job is to get the Pedometer data from history within a specified period of time and return that to Unity for later use. I am confident in my C# code, but Obj C part is what troubles me.
I'm afraid I have some potential memory-leaks should the requests come more oft... | stackexchange/codereview |
Is this an OK way to handle access to database connection both inside and outside of classes?
I used to include a PHP file -- database.detl.php -- at the very top of my index.php file containing the following code:
try{
$dbh_options = array(/*...*/);
$dbh = new PDO('mysql:host=localhost;dbname='.db_name.';chars... | stackexchange/codereview |
Maze puzzle
A 1 in input matrix means "allowed"; 0 means "blocked". Given such a matrix, find the route from the 1st quadrant to the last (n-1, n-1).
I would like to get some feedback to optimize and make this code cleaner. Also let me know if O(n!) is the complexity, where n is the dimension of the maze.
final class... | stackexchange/codereview |
I just started learning recursion and memoization, so I decided to give a simple implementation a shot. Works with some simple test cases I came up with. Is there anything I can add to make this more interesting? I'm not sure if I can update the return type with generics somehow depending on the input "n" for long, Big... | stackexchange/codereview |
I made a simple dungeon generator in C# using MonoGame that works by placing rooms in a grid and connecting them via "tunnels". I would like feedback on how this could be improved in terms of efficiency and code style. Also, please ignore the Render() function in DungeonGenerator.cs as it is only temporary.
Here is one... | stackexchange/codereview |
After the feedback for my last script, I realized I should be using functions and trying to adhere to the style guide. I tried to do that here, though still very beginner.
The rounding in Python confused me a bit, and originally the program got stuck for some numbers when the range narrowed down to 1. I think it should... | stackexchange/codereview |
Another more simple project from my CS1 class that I didn't upload while I was sick last week:
Write a program that computes all of the following statistics for a
file and outputs the statistics to both the screen and to another
file: the total number of occurrences of characters in the file, the
total number of... | stackexchange/codereview |
I have a task wrapper which stores tasks, their CancellationTokens and of course their names (botName). botName is important, because when I want to stop a bot/cancel task, I will have to find it in the collection.
I wonder if there is a better collection to do that, because it looks ugly, especially the CancellationTo... | stackexchange/codereview |
What is a better way to create this select statement? I tried to just select 'u' and 'us', but the object properties were not accessible when I did this.
var userSubmittedRequests = (from u in db.TimeRequests
join us in db.UserManagers
on u.Emplo... | stackexchange/codereview |
I am learning Go and as an exercise I did this challenge from Code Golf (without the golfing), where an ASCII art snowman is drawn from a combination of body parts, based on an 8-digit code taken as command line argument.
For example:
$ ./snowman 12431312
_===_
(-.O)
<( : )\
( : )
As a minor extension I decided... | stackexchange/codereview |
My code does exactly what I want it to. However, being relatively new to VBA, I feel it could be a lot more efficient - namely I think I have overused loops and worksheet functions which are slowing it down. At the moment it takes around 3 minutes for ~15k rows of data.
Currently it's more of a combination of separate ... | stackexchange/codereview |
Inspired by Extensible and testable FizzBuzz I have decided to write my own implementation, partially based on my own answer and on the other answers.
First a warning to all of you: Never make such complicated code for such simple jobs!
Now the basic requirements of the code:
Should be capable of solving the FizzBuzz ... | stackexchange/codereview |
I have created a little console tool that simply does commands that you enter.
The commands are stored in a txt file. Right now I only got 2 commands: getTime and getCommands.
Pretty simple, but I'm not sure I'm doing anything the most optimal way, which is why I am asking here. I was thinking about creating a whole c... | stackexchange/codereview |
I have a module in Python for dealing with SVG paths. One of the problems with this is that the SVG spec is obsessed with saving characters to a pointless extent. As such, this path is valid:
"M3.4E-34-2.2e56L23-34z"
And should be parsed as follows:
"M", "3.4E-34", "-2.2e56", "L", "23", "-34", "z"
As you see, anythin... | stackexchange/codereview |
Any suggestions for improving this? I'm hoping for some JavaScript object structure / code integrity type recommendations rather than style or CSS.
var list = [
{name: 'Afghanistan', code: 'AF'},
{name: 'Åland Islands', code: 'AX'},
{name: 'Albania', code: 'AL'},
{name: 'Algeria', code: 'DZ'},
... | stackexchange/codereview |
I have been using the w3 org's JavaScript Best Practices web page's examples for coding an object literal for a game.
It is my understanding that I should use this to keep all my variables and arrays that are not associated with/inside functions. I should then use methods to access and update the values and arrays.
I w... | stackexchange/codereview |
This is an OOP question and probably answerable even if you don’t have PHP knowledge. (A side note – we are learning PHP OOP and decided to create a github to hopefully help others learn this and other best practices a bit easier, https://github.com/nizamani/PHPBestPractices1-OOP if you are interested. PRs, issues etc ... | stackexchange/codereview |
Should I leave the Default Route in if it's not adding any benefit?
I have a RouteConfig.cs file that looks like this:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Dashboard",
url: "{controller}/{action}",
... | stackexchange/codereview |
Here's an implementation of selection sort, that sorts an array in ascending order.
Please let me know of any improvements/optimisations that can be done.
import java.util.List;
public class SelectionSort {
public static void start(List<Integer> arrayToSort){
for(int i = 0; i < arrayToSort.size(); i++) { ... | stackexchange/codereview |
I tried to implement union find (disjoint set data structure) algorithm in C++. There I used unordered_map data structure. Is there a better way of doing this using any other data structure.
While finding the root I have used the following way.
int root(int i){
if(i != parent[i]) parent[i] = root(parent[i]);
... | stackexchange/codereview |
In the process of over-engineering a custom library, I implemented expression SFINAE to detect and call specific member functions only if they exist. I also let classes overload these functions and then I call the "best" available function based on an order of precedence.
Example
The library will accept classes that ha... | stackexchange/codereview |
I'm adding an onclick listener to the whole document then checking the source of the click. If the source of the click contains the attribute data-widget I want to go to the appropriate action. I did it but I'm hoping for a more efficient way of doing things and if I can do without the self invoking function.
<div dat... | stackexchange/codereview |
This code works. It is designed to retrieve website data directly, parse it, and open it as normal. I will develop it further later. Right now I want to know if there is any way to improve efficiency, such as not using a file etc. I would also like to know if my code could be made more pythonic (this would include PEP ... | stackexchange/codereview |
I am developing a service application that would implement a peer to peer messaging system. I am wondering if my following code is the best approach. It works, but I am naive and it would be nice to have validation from experts for performance and reliability.
There would be about 5 plugins and a large number of messag... | stackexchange/codereview |
I recently overhauled my solution to Project Euler Problem 23 (which asks for the sum of all positive integers which cannot be written as the sum of two abundant numbers) to move it from an imperative style to a functional style and tried to increase its speed. However, the performance is still slow. I have clocked thi... | stackexchange/codereview |
This is a follow-up question for A recursive_transform_view Template Function which returns a view in C++. I am trying to revise the structure of recursive_transform template function implementation in C++. As the suggestion mentioned in Davislor's answer, For dealing with dangling reference issue, the updated recursiv... | stackexchange/codereview |
I'm looking to let people define arbitrarily nested lists of lists and return a random json document for them. Right now the assumption is that if you have a structure like this:
[item1, item2, [item3, item4]]
The desired document is:
{item1: value,
item2: {
item3: value,
item4: value
}
}
This is my curre... | stackexchange/codereview |
I finished an output stream-based pseudorandom number generator, that works based on the current time and output data.
Here is the header's code (entrostream.hpp):
#ifndef ENTROSTREAM_HPP
#define ENTROSTREAM_HPP
#include <iostream>
#include <cstdlib>
#include <climits>
#include <sys/time.h>
#include <queue>
#include <... | stackexchange/codereview |
I have a script that allows me to open and view the general notes I save at work and studies. I have this particular function, and I am afraid it will become overwhelming. How should I approach this?
The purpose of the function is to parse summary information into a JSON and record stats like last modified, times viewe... | stackexchange/codereview |
So I got this code;
public bool Guest
{
get { return GetValue("guest", true); }
set { SetValue("guest", value); }
}
I am wondering if it would be possible to shorten that as I would like to keep the code very clean, I've tried some stuff
public bool Guest => GetValue("guest", true)
Bu... | stackexchange/codereview |
I've been improving some of my old sequence generators that worked with generics and lambdas in order to support binary operators for the specified T:
public abstract class Sequence<T> : IEnumerable<T>
{
public IEnumerator<T> GetEnumerator() => Generate().GetEnumerator();
IEnumerator IEnumerable.GetEnumerator... | stackexchange/codereview |
I am having performance problems with the following python function:
def remove_comments(buffer):
new_buffer = ''
lines = buffer.split('\n')
for line in lines:
line_wo_comments = line.split('--')[0] + '\n'
new_buffer = new_buffer + line_wo_comments
return new_buffer
When buffer is very ... | stackexchange/codereview |
Consider the below:
public int DoSomethingComplicated(ComplicatedObject input)
{
try {
return input.Analyse();
}
catch(CustomExceptionOne ex1)
{
throw;
}
catch(CustomExceptionTwo ex2)
{
Log(ex2.Message);
return -1;
}
}
Obviously I have abstracted quite... | stackexchange/codereview |
For fun and to learn a bit, I decided to implement a bidirectional map in Ruby, relying on Ruby core libraries where possible.
Its behavior is intended to be that of a Ruby Hash, but one in which 'values' are also hashed as keys for quick reverse lookup. I've implemented nearly all the methods from Hash, except those I... | stackexchange/codereview |
I re-used this answer from this StackOverflow answer to simulate a function pointer approach available in high-level languages like C.
While using this approach in Python, the dictionary I am defining to map the functions needs to be defined after all the functions are defined before. It makes the dictionary definition... | stackexchange/codereview |
I am kind of new to programming. Picked up some Perl about a year ago and now learning some Python. I am pretty confident in Perl, but Python seems un-natural to me.
I wrote a little script that parses log files and indexes them into Solr in JSON. This is for some reporting.
I wanted to see if there are more pythoni... | stackexchange/codereview |
Is ProtectedObject really secure? Otherwise, do you have any advice?
public class ProtectedBinary : IDisposable
{
private byte[] pBArray;
private int originPBArraySize;
public ProtectedBinary(byte[] data)
{
originPBArraySize = data.Length;
Pad(ref data);
ProtectedMemory.Protect(... | stackexchange/codereview |
The code below does what I need it too but it is ugly and clunky. If I could set the list of cells I want to retreive data from as an array that is declared somewhere, then I could loop through that array rather than declaring each individual cell.
As you can see below, I have had to declare each of the cells I want in... | stackexchange/codereview |
I have two divs as seen in this JSFiddle. To recreate the problem, keep clicking on the Gray container till both divisions touch each other.
The purpose is to execute a certain function once the green div touches the red one. The problem is that, this step callback as seen from the following code and demo, gets called ... | stackexchange/codereview |
Recently, I found myself frequently writing notification managing facilities. That is, one can register as a receiver by providing a callback, and another can send a notification to all registrants by invoking their corresponding callbacks. I had been bothered by re-writing this similar code again and again. Finally, I... | stackexchange/codereview |
I'm learning Python and I'm building a basic random numbr generator. The code below works as expected. I'm just wondering if it uses best practice / can be made better.
Some future considerations might be adding a way for users to pick a random that isn't limited to 0-50 or 0-100, and finding a way to scale the number ... | stackexchange/codereview |
I've seen the pattern:
<?php
if ($node = node_load(30) && $node->type == 'bogus') {
print $node->title . 'is bogus';
}
But when I tried to use it I got a warning: variable not defined... Has this pattern of declaring variables while you loop in an if been deprecated?
| stackexchange/codereview |
Here is my program that turns numbers into text. It can be extended to millions, billions, trillions and so on. Please review my code and here is what I expect from the users:
Is there any better variable names, function names, you can give me? Or my given names are okay? If you've better variable name ideas, please ... | stackexchange/codereview |
So someone requested a Regex Builder / Assistant for Rubberduck and since my CS class had been covering the topic only recently I was thinking to myself: "This sounds interesting, you should do this".
Long story short, a day of designing and a weekend of implementation (and some more polishing) as well as a few reviews... | stackexchange/codereview |
As I'm reading the Java code of some other people, I found him using an approach of assigning a format string to a variable and using the variable for String.format in the code:
private final static String URI_SUFFIX_FORMAT = "view/%s";
@Inject
private UriBuilder uriBuilder;
public void buildUriForMusic(String dir)
{... | stackexchange/codereview |
The following exercise is from an Assembler-course I'm taking:
Write a program that takes a number x as input, and returns:
0 if x is even.
1 if x is odd.
Full exercise-page here: GitHub
Here's my solution:
format PE console
entry start
include 'win32a.inc'
; ===============================================
secti... | stackexchange/codereview |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.