instruction stringlengths 71 71.9k |
|---|
This is my very first attempt at Python and whilst the script works perfectly, I'd like to see if I'm missing anything obvious or doing anything particularly stupid. I think this runs on Python 2.7, but I'm not 100% sure.
Goal:
The goal here is to grab a task and its elements (records contain BLOB PDF data) and write ... |
I need a constant (dictionary with values and default return value if there are no defined value for a key). Searching for any ways to simplify the code.
Without a default value I can simply define a dictionary like this:
REDUCE_VALUE = {
"honda": 0.95,
"suzuki": 0.85,
"yamaha": 0.87
}
But with a default v... |
Okay so this is NOT my code, I just inherited it. Seems it has an obvious bug that it will only return the first email despite being called "GetEmails". My main concern is actually that it takes forever on some pages. The regex looks over complicated, but regex are something I have never really 'got into' hence posting... |
I have the following situation:
I have...
Models like ServerRoom and ServerCabinet
Repositories of the Model instances (in-memory collection)
PersistenceServices which are interfacing the persistence-method I chose (mssql db)
The problem I am facing is repetition.
Basically, the implementation of a PersistenceService... |
I wrote an answer to another question about the same subject and a new implementation, but instead of just posting my code there I think it's a good chance to see what can be improved on my own code.
#include <algorithm>
#include <array>
#include <iostream>
#include <iterator>
#include <map>
#include <tuple>
#include <... |
This is a music downloader and transcoder based on Youtube-Dl and VLC. It is written in Python 3. The PAFY Python module is required in addition to VLC. Currently, the cancel button is not functional and there is still a pop up command prompt, though this does not matter and should be disregarded.
import urllib.request... |
I run subprocesses with lot of output (compilation of Unity 3D projects).
I use log parsers to find known issues.
class LogParser(object):
def __init__(self):
self.report = []
def __call__(self, output: bytes):
for decoded_line in output.decode().splitlines():
self.parse(line)
... |
I'm trying to create a grid of settings for the user to edit. I'm using a PropertyGrid at the moment, but I'm open to alternative solutions.
My two big issues are that I don't love the look of the property grid. It looks overly complex for the small number of properties that can be edited. Also, I dislike how verbose ... |
I have written a simple prepared statement factory in Java and would like some feedback on how "secure" it is. By "secure" I mean that I can pass any old garbage in as a string and it should not allow any form of SQL injection or modification of the query in an undesirable way.
Here is the code for the factory:
/**
* ... |
I previously asked this question but have since improved my code: Substituting bookmarks in a Word document with data combined from an Excel sheet
What happens in the code:
Information about a list of suppliers needs to be consolidated into a Word document that maintains the same layout on all pages. To do this, a doc... |
Here is a caching code of a nodejs / typescript app using lru Cache module from https://www.npmjs.com/package/lru-cache.
For various reason i need to setup separate caches: one for homeCache another one for detailThreadCache... but this is just the beginning I may need to set up more.
This code is working, but how woul... |
I'm currently using Backbone to generate a carousel slider. In my View, I have an initialize function that looks like this:
var SlideModel = Backbone.Model.extend({
defaults: {
id: null,
source_url: null,
date: null,
slug: null,
link: null
},
idAttribute: '_id'
});
... |
My Python code is converting XML attributes in an ElementTree to appropriate values. How do I best convert a value in this dict to a float() if it exists, or else get None?
Best I have now is:
attr = etree_elem.attrib
self.radius = float(attr['radius']) if 'radius' in attr else None
...
if self.radius:
# do stuff usi... |
In a completely overkill BrainFuck lexer/parser I've presented the lexer, parser, interpreter and syntax tree classes. With this post I'd like to go over the lower-level Token and Span mechanics.
Each token has a Type property that returns a TokenType enum value:
namespace BrainFuck.Tokens
{
public enum TokenType
... |
I have two tables, devices and device_properties.
The devices table columns are as follows:
id
ip
mac
device_property_id
created_at
updated_at
The device_properties table columns are as follows:
id
property_name
cli_enabled
created_at
updated_at
At the moment I have the following code to retrieve an array of devic... |
First of all, the code:
struct Bucket<H, V> where H: Ord
{
hash: H,
values: Vec<V>
}
impl<H, V> Bucket<H, V> where H: Ord {
fn new(hash: H) -> Bucket<H, V> {
Bucket {
hash: hash,
values: vec![],
}
}
}
pub fn bucket_sort<T, F, H>(values: Vec<T>, hasher: F) -> Vec... |
I needed an asynchronous parallel ForEach mechanism so I could enumerate an enumerable by N degrees of concurrency and process an action for each item. Searching around, my code was modeled/merged from a few posts I found.
The tests I have been running are:
Run body() to completion
Inside the body(), do a Cancellati... |
The purpose of this code is to change each column to a row, and assign keys to each value for the new array according to the old array. I would like to know if there're other ways to optimize it.
<?php
$arr = [
'name' => ['a', 'b', 'c'],
'age' => [ 2 , 1 , 3 ]
];
$result = [];
$keys = array_keys($arr);
f... |
A simple implementation of Naive Bayes, as I'm a Haskell beginner I've tried to put an emphasis on clarity and documentation. I've tried to incorporate the feedback from a similar question. This is the main module, the full code can be found here.
Update: implemented hlint suggestions.
module NB where
import qualified ... |
I have the following functions which help me to open a text file and remove any blank (empty) lines:
def fileExists(file):
try:
f = open(file,'r')
f.close()
except FileNotFoundError:
return False
return True
def isLineEmpty(line):
return len(line.strip()) < 1
def removeEmptyLine... |
My Implementation of a FIFO queue. I am mainly curious about my initialization of empty generic arrays.
public class Queue<T> {
T queue[];
public Queue()
{
queue = (T[])new Object[0];
}
public T pop()
{
T queue2[] = (T[])new Object[queue.length-1];
T obj = queue[0];... |
how can I optimalize this code?
#include<bits/stdc++.h>
using namespace std;
class Graph {
int V;
list<int> *adj;
void DFSUtil(int v, bool visited[]);
public:
Graph(int V);
void addEdge(int v, int w);
void DFS(int v);
};
Graph::Graph(int V) {
this->V = V;
adj = new list<int>[V];
}
voi... |
I'm currently taking a JavaScript class. I'm fairly familiar with JavaScript and coding in general, so I decided to teach myself functional programming on the side. It's been great, my teacher's fine with it. However he doesn't really know much about functional programming, so it's difficult for him to critique my desi... |
To be able to apply various colors to the console I created a ConosoleColorizer. It's really simple. It just takes an XML and renders it to the console with the colors specified.
The element names are actually optional and can be any names. They are only required to parse the XML. What matters are the attribute and col... |
I have a non-trivial list comprehension in Python. My goal is to take a whitespace-delimited list of strings from an XML attribute — which may not exist — and look up the corresponding constant in my module — which may not exist — and create a set of the results.
What's the accepted way to format such a beast? They a... |
The objective of the program is to check that the weight of the bag that the user inputs and then calculate how many coins are needed to the added/removed to ensure the bag has the right amount of coins in. It needs to display the difference in weight and the number of coins to be added/removed and a total value of coi... |
I was writing some code that required the user to input a number, which was then stored in a variable. While testing the code I input a number larger than the variable type would allow and I got an variable overflow error. So I wrote this code to prevent that from happening. It works, but I was hoping there was a mor... |
_____ _____ _____ _____ _____ _______
/\ / ____| / ____| |_ _| |_ _| /\ | __ \ |__ __|
/ \ | (___ | | | | | | / \ | |__) | | |
/ /\ \ \___ \ | | | | | | / /\ \ | _ / | |
/ ____ \ ____)... |
I did a super simple version of Conway's Game of Life and would like a review.
public class Conway {
String [][] grid;
int [][] neighbors;
int [][] directions = {{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1},{-1,0},{-1,1}};
Conway (int gridSize) {
this.neighbors = new int [grid... |
I have the following solution for the Trip problem from Skiena's and Revilla's Programming Challenges (full problem description here).
//#include "stdafx.h"
#include <iostream>
#include <string> //Always import <string> if piping std input to a string in .net
#include<algorithm>
#include<math.h>
#include<fstream>
usin... |
I have simulated the conversation between a caller and receiver using fork and pipe. The parent process is the receiver and the child process is the caller. Each message is terminated by a newline.
The program seems to be running correctly. Should I take care of any other condition?
#include <stdio.h>
#include <string.... |
An L-system is a rewriting system that can be used to generate fractals and space filling curves, because of its recursive nature.
Some L-systems for mathematical curves can be found here.
An example L-system:
Axiom:
$$FX+FX+$$
Production rules:
$$X → X+YF$$
$$Y → FX-Y$$
Angle:
$$\theta = 90$$
In this example, F means ... |
This was the problem from "30 Days of Code" on Hackerrank:
Given set \$S = \lbrace{1,2,3,\dots,N}\rbrace\$, find two integers \$A\$ and \$B\$ (where \$A \lt B\$), from set \$S\$ such that the value of \$A\&B\$ is the maximum possible and also less than a given integer, \$K\$. In this case, \$\&\$ represents the bitwi... |
This is a simple Ruby program to analyze the number of lines characters speak in Shakespeare's Macbeth using Nokogiri and open-uri to parse a given url containing xml. I wrote this as practice getting used to Ruby and TDD.
I'm new to Ruby so I'm wondering if anything looks strange to more experienced Rubyists.
Note: I ... |
I receive HTML-encoded text that includes named and numbered entities, and I need the decoded HTML.
There were just too many bad solutions for this online.
I use regex pattern &(#x|#){0,1}(\w{1,8}); to find the entities in an HTML text (capturing the numeric prefix and the numeric expression), and I use a Static Script... |
I'm working on a car move problem. Suppose we have origin parking position for each car, [-1,1,2,3,7,6,4,5] (which means first position is empty, car with ID 1 parked at 2nd position, car with ID 2 parked at 3rd position), we want to find the minimal move to re-park car as specific desired positions. For example specif... |
I have a simple javascript randomizer that compares two random numbers with values 1 to 6.
I want to get a good estimate about the probability of the first been greater than the second. I could do it using math, probability theory e.t.c. but lets say that I want to stick to javascript. Using millions or billions of itt... |
I've got these two template functions responsible of adding/removing actors in-game in GameEngine.h:
template<typename T>
void add(T actor);
template<typename T>
void remove(T actor);
And these arrays:
std::set<std::shared_ptr<Tickable>> tickables;
std::set<std::shared_ptr<Hitbox>> hitboxes;
std::set<std::shared_ptr<... |
In our application we have data which needs to be shared between multiple threads. Now and then we ran into a race condition and we could not figure out where that was. So I have implemented a deadlock watchdog.
It is supposed to be used like this (example):
public bool GetFromElementExistsCache(string id)
{
using (n... |
The project below is about a Telegram bot that implements both inline and offline modes. The idea is to get a brief info about a book, searched by title(it's author, rating, short description). I decided to retrieve the info from GoodReads. Besides the parse implementation, I have trouble in correctly accessing the Tel... |
I'm pretty new to ruby and programming in general.
I had an idea for a fun little project that I could use to gain a little experience. I wrote a simple program that takes a 4 bit binary sequence (ie. 1001, 1110, etc) and converts it into its decimal counterpart (ie 1111 = 15). I got the program working but even I can ... |
Those unfamiliar with that algorithm can have a deeper look here, in a few words, there are two arrays where you subtract each element ar1[0][0]-ar2[0][0] and add that result using the absolute values. My implementation is this:
#include <stdio.h>
#include <stdlib.h>
#define LEN(arr) ((int) (sizeof (arr) / sizeof (arr... |
It's my university task. Can I get some opinions on it?
#include <iostream>
#include <vector>
using namespace std;
string toBinary(short n) {
string r;
while(n != 0) {
r = ( n % 2 == 0 ? "0" : "1" ) + r;
n /= 2;
}
return r;
}
int has_even_parity(int c) {
int k = 0;
if (c != 0)
k+... |
I have a very basic XMLHttpRequest function that would be used with web workers.
I would like to know how I could improve it to handle possible errors better:
var ThreadedXhrRequest = function(url) {
var worker = new Worker("xhrWorker.js");
worker.postMessage([url]);
worker.onmessage = function(d) {
... |
I often find myself having to do np.intersect1d() multiple times because I need to find the intersection of a number of list like or array like things. So I ended up creating a function for it. Though, if possible I'd like to simplify / and or speed up the code for when the input becomes rather large.
def overlap(spli... |
I have to develop a class that creates new files. If a file with the given name already exists, it should be renamed by addition of the timestamp to the file name. The file name should be human-readable, so I can use neither UUID nor createTempFile. The code works, but looks too bulky.
public class FileBackup {
/*... |
I have a quiz app that gets data from a questions.json file using AJAX, loads them into my script file, and then use Handlebars to compile templates so I don't have to mix HTML in my JavaScript code. I welcome any improvements on my current code.
app.js
(function($, Handlebars) {
"use strict";
// Get all the q... |
Is this a correct linked list implementation of binary heap insertion? This is not a homework exercise.
public BinaryHeap insert(int value , BinaryHeap node , int count)
{
//1. Insert into a binary tree breadth wise( satisfy complete binary property) (left to right)
//2. Once inserted ,fix the tree... |
I put together a code will allow me to toggle a class and save it in local storage.
Now I need to add 2 more classes to be toggled and be saved in the same manner.
I don't know how to iterate properly with the code and the DOM to achieve this.
This is my "semi-working" example:
http://jsbin.com/nimekebura/1/edit?html,... |
I wrote a node script to traverse a folder of hour-long mp3s and upload them to Mixcloud via their API. It works, but I suspect it's fairly inefficient - the computer it's going to run on at our radio station is an old white Macbook. Would appreciate any insight for how to improve it.
const restler = require('restler... |
I wrote a little bit of code to brute force disprove the Euler proposition that states:
$$a^4 + b^4 + c^4 = d^4$$
has no solution when \$a\$, \$b\$, \$c\$, \$d\$ are positive integers.
I'm no mathematician, but reading around this, at least one solution was found by Noam Elkies in 1987 (a = 95800; b = 217519; c = 414... |
This is my wrapper, how can i improve this? (With a Singleton too)
<?php
define("DB_HOST", "");
define("DB_USER", "");
define("DB_PASS", "");
define("DB_DATA", "");
class Connection extends PDO{
public function __construct($host = DB_HOST , $data = DB_DATA , $user = DB_USER , $pass = DB_PASS){
... |
I'm reviewing MIT Introduction to Algorithm lectures/exercises and am trying to implement a one dimensional peak finder algorithm.
I've got a working copy but it's a bit messy and I've had to put some array size constraints to get it working properly. How can I improve this implementation?
def peakfinder(arr):
if ... |
I have implemented a Gibbs sampler to generate textured images. According to the beta parameters (array of shape(4)), we can generate various textures.
Here is my initial function using Numpy:
def gibbs_sampler(img_label, betas, burnin, nb_samples):
nb_iter = burnin + nb_samples
lst_samples = []
labels = ... |
I am trying to turn
namespace DevComponents.WpfEditors.Primitives
{
/// <summary>
/// Interaction logic for EditorFreeTextButton.xaml
/// </summary>
public partial class EditorFreeTextButton : EditorButton
{
public EditorFreeTextButton()
{
InitializeComponent();
}... |
I'm lately messing up with handling joystick in java.
So here is the thing. I wrote a simple class that handle input from joystick, but I'm no certain if I'm doing it well.
Here is what I want to achieve. So i have joypad, I'm using jinput from LWJGL 2, and want to bind axis and buttons state to Javafx application, an... |
Recently, I was learning about greedy algorithms. One example that was given was an algorithm for exchanging a given money amount using the smallest number of coins. After the lecture, I wrote a C program implementing this:
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
static int compareDenominations(const... |
I have always disliked the way PHP printed stacktraces, coming from a Java world. So I decided to implement my own ExceptionFormatter, a class that will format Exceptions/Throwables to my liking.
class ExceptionFormatter
{
/** @var \Exception|\Throwable */
private $exception;
/** @var string */
privat... |
I making simple multithreading signature program (it calculate SHA256 hash for parts of file). Please check my code and I would be grateful if you tell me about errors in my code
Program.cs
using System;
using System.IO;
namespace Signature
{
class Program
{
public static TaskQueue Tasks;
publi... |
This is an mqtt driven, interactive, and asynchronous remote shell daemon written in bash. I call it "MqSH" or simply "mq". It works with bash, the busybox ash shell, and perhaps other Bourne-like shells. It's designed for embedded devices with low system resource, so I wrote to be friendly to busybox-based systems.
It... |
I have written the following thread pool implementation in C++14.
It appears to work fine on my system, but I am looking for a second opinion on the thread safety of my implementation and any other possible implementation flaws or concerns.
#include <atomic>
#include <condition_variable>
#include <exception>
#include <... |
I use MultiMarkdown tables more than I thought I ever would. In my .md files, I would like the source table code to be neat, evenly spaced, and resemble (in an alignment sense) the final HTML rendered table.
Solution
Select the source of the table, press a hotkey on my computer, replace the untidy table with the tidy t... |
I am working on Oracle SQL. What I am trying to do is:
Query a record with ID
If the record does not exists use user input value
If the record exists, compare last_login_date column and user input value (I put to_date('20160401', 'yyyymmdd') then pick recent one)
Add not_change_day to result of 3, then compare the val... |
I want to check whether or not an object exists in an array given its key (key is not unique).
The object takes the form:
class item {
key: string,
value: (string|int|boolean),
id: Guid
}
And this._items is an item array.
First approach is simply filtering the array and checking its length:
has(key) {
... |
I am a beginner Java programmer. I have just finished up an assignment and would appreciate some advice and/or criticism on my program. For context, I have the assignment details, followed by the full code below:
Create an Employee Records program that incorporates the following properties:
employeeIdNumber;
firstNam... |
This is an interview question from Interview Cake:
Given a list_of_ints, find the highest_product you can get from three of the integers.
The input list_of_ints will always have at least three integers.
I'm looking for feedback on how to improve readability, space, time complexity, using Python idiomatic code and g... |
Total newbie here and wouldn't mind learning from Rubyists to look at how I tried to solve this challenge.
I started with 2 variables n which starts at 0 and total which is an array where I intend to push n if it satisfy the condition set by the 2 modulo. Using the until loop with a max of 1000, my intention was to cha... |
My program makes a conversion between Roman and decimal numbers. Can you give me some advice on how to make it look more readable or to improve in general?
Would code extraction of similar-looking logic from switch cases into helper methods do the job? Or can we take some other approach and use recursion, enums or regu... |
I wrote this in 78 minutes as part of an application to an internship program. We were allowed to use whatever language we wanted, so I picked Rust because that's what I use the most. I'm a Sophomore CS/Data Science major and I just wanted to get a feel for how you more experienced among us feel about what I made.
I'... |
I have submitted here my solution to the LCD Diplay programming challege(detailed here)
Please review my code and let me know what you think.
// ConsoleApplication3.cpp : Defines the entry point for the console application.
//
//#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
/*We use... |
As a pet project I implemented a neural network. I am looking for general advice, since I am a self tought programmer, but I have few specific questions I stated at the end of this post. Let's dig into it:
Code
Neuron.hpp:
//------------------------------------------------
// NEURON.HPP
//-----------------------------... |
Is there a way make the code better so that it does not have repeated code?
int totalDistance;
if (totalDistance < pow(10, 3)) {
cout << "\nTotal (approx) travel distance = " << totalDistance << " million km\n" << endl;
}
else if (totalDistance < pow(10, 6)) {
totalDistance = totalDistance / pow(10, 3);
co... |
Telegram Bot that retrieves book information from GoodReads
I've created a Telegram bot that implements the inline/offline modes to get the brief info about a book, searched by title(inline mode) or with command /random. The data is retrieved from GoodReads. I was wondering how can I modify the body of 'description', s... |
I've created function that will display a league competition from the total team numbers.
For example if we have 4 teams it will display (a vs b) vs (c vs d)
and if we have 5 teams it will diplay ((a vs b) vs c) vs (d vs e) and so on. It will display the competition looks square or equal.
here is the complete code :
... |
To sum up my project was about making cool animation of titles appearance with an effect of a colored block coming from one side while expanding and disappearing from the others side while contracting and let the text appear.
My goal was to achieve something simple, that can be used again easily on different elements j... |
The project is an API that will itself make HTTP requests to external webservices.
Since this is PHP, we actually chose to use guzzlehttp.
Now the library itself doesn't matter much, but I'm scared we'll be stuck with it if it ever has a major change (it already happened in the past).
So I thought I'd create an inte... |
I have been using Tweeepy to connect to the Twitter Streaming API to collect tweets, parse that data, and then write select fields to a CSV file. Based on some examples that I found, I put together the following code to manage that connection. One thing that I had to work around was how to handle the connection getti... |
I'm trying to come up with a smart wordpress inspired PHP function that builds an url for my CMS. It has some different requirements that are almost all fulfilled so far.
Must use correct domain
Must be able to use subfolder (Eg. /blog/index.php)
Must be able to specify protocol (if http or https)
Must accept queries ... |
What can be done better? What should I learn to make these tasks better and more efficiently?
The template (template.h):
#pragma once
#include <iostream>
template <typename TData>
class CArray
{
public:
CArray(int capacity = 0);
CArray(
const CArray & _array
);
~CArray();
void push_back(
const ... |
I've completed this Tic Tac Toe simulator in java and so far it's working. It's just supposed to generate a pre-played game and announce the winner. I'm required to use a 2D array and this is the way I've found to get it done. But I ask more experienced developers if there is a way to do this that is a little less conv... |
For one of my assignments, we were asked to create a data structure similar to Bags using dynamic arrays where the order would be important - which I was able to do successfully, that is, the code that follows works fine. We now have to optimize the code according to the memory usage and timing.
One of the functions th... |
I've created an asynchronous parallel ForEach mechanism so I could enumerate an enumerable by N degrees of concurrency and process an action for each item. Additionally, I have the option of stopping when first exception is encountered or processing the entire enumerable and returning all exceptions at the end. I'm t... |
I am new to concurrent dictionaries and all their new methods involving "Try". I have coded a simple method below that retrieves roomInformation from a dictionary (roomInformation is a class) and then prints it if it exists as well as returns true.
Have I done this right? is there a better way? please do let me know i... |
I have this little class for parsing, comparing and sorting semantic versions. I did my best to implement the specification at semver.org with one exception - it doesn't support the build metadata. Now you can tear it apart ;-)
I removed all parameter checks to make it shorter.
[DebuggerDisplay("{ToString(),nq}")]
publ... |
For an outsourced job (implementation of a network client) I will provide a simple server for protocol-testing. This is the code.
Do you consider this code readable/ comprehensible?
using System;
using System.Text;
using System.IO;
using System.Net.Sockets;
namespace SimplePictureReceiverServer
{
class Program
... |
In our latest Veracode scan for an application, I have come across the issue of Improper Resource Shutdown or Release. It is pointing at a function. Here's what the code looks like:
Imports System.Data.SqlClient
Public Class DAL
Public Shared ConnString As String = ConfigurationManager.ConnectionStrings("connect... |
I have spent a decent amount of (waaay too much) time trying to write the below function and get my head around recursion. The aim was to return all permutations of an int vector (assuming no duplications of input). I would like to know people's thoughts on my code. One downfall that I can identify is that it is pretty... |
It feels like there's quite a lot of code involved in order to manually build up an animation using the libGDX framework. In my specific case, I am creating a number of animations for a portrait view of a character. The character will do things like talk, blink, and laugh. There are a handful of different characters t... |
I am new to Ruby and not familiar with a lot of Array features. I feel like this code can be written in a couple of fewer lines.
The idea is: I have a Definition class and a Field class. I abstracted them as Hashes to make my life easier although they should be classes.
Definition contains an Id and a Name
Field conta... |
I have this Python project to draw tessellated triangles on the screen. It takes the height to form the size of the triangle, cols to specify how many triangles on a line, and rows which is how many lines it outputs.
This program has taken me some time to put together and I'm not sure if this is the best way to do this... |
Because my job needed something like this, I created a Python script that'll connect to an IMAP server, get all the emails, and then calculate the very rough daily average of emails received to the Inbox (as well as the 'smallest' number of emails handled per day, and the 'largest' number of emails handled per day, for... |
The below may not look like much, but the ability to call methods in other classes, offloading all the work onto other classes from MainClass, and returning a variable to be passed to the next method is a rather large leap for me at least.
using System;
namespace CSharpTutoriel
{
class Work
{
public st... |
I'm a node beginner and I'm trying to write fewer lines of code by finding out which lines are redundant.
var express = require('express');
var app = express();
var server = require('http').Server(app);
var port = process.env.PORT || 8080;
var mongoose = require('mongoose');
var passport = require('passport');
var ... |
This is a follow up to Maximum product of 3 integers in an int array using Python
Changes to the code include renamed variables for improved readability and I added more test cases.
import unittest
def highest_product(list_of_ints):
max_seen = [float("-inf"), float("-inf"), float("-inf")]
min_seen = [float("i... |
I'm trying to print a diamond of asterisks of an arbitrary size. I'm new to F#, so I'm interested in virtually any feedback, but especially adherence to idioms, convention, and functional orientation.
module Diamond
open System
let rangeWithInverse (max) =
List.zip [ 1 .. max ] [ max .. -1 .. 1]
let listAscDesc ... |
I am currently using the BestFirst algorithm to solve the puzzle 15. It works well when I have a simple inputs and takes about 1-20 seconds to solve the puzzle. But when it comes to complicated inputs, it might takes forever to run. I'm just wondering if there is any way to improve my algorithm's performance.
Main.java... |
Here is a continued discussion (Game where two players take turns picking numbers until a target sum) from here since my previous code has bug, I fixed it with totally new algorithm implementation.
Working on the problem of sum game. Suppose we have consecutive numbers from 1 to n, and an expected sum number, there are... |
This solves Project Euler 4: Largest palindrome product using Python (not limited to 3 digit numbers). I need suggestions for improvements to either the Python code or the math/algorithm since time of execution increases exponentially as number of digits in multipliers increase.
A palindromic number reads the same bot... |
I've written a Node js server that create, read, and update user data from a SQL server hosted in Azure. Clients connect to the server using a standard TCP socket, every message sent or received will be encrypted/decrypted using AES 256 CBC.
Communication protocol
TCP is used to create a simple communication mean with... |
I stumbled my way through some Rust yesterday and today to make a simple ASCII art API. It can draw lines, circles, and a canvas.
use std::collections::HashMap;
#[derive(PartialEq, PartialOrd, Debug)]
struct Point(u32, u32);
#[derive(PartialEq, PartialOrd, Debug)]
struct Dimension(u32, u32);
#[derive(PartialEq, Par... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.