instruction_seed stringlengths 71 95.1k | _source stringclasses 1
value |
|---|---|
this is my 2nd project on Python. I created a game of Noughts and Crosses(Tic-Tac-Toe) that you can play against the computer. What are your thoughts on my implementation of the game? Is there anything I've missed or could improve upon?
I did think about adding a figure window and making it more interactive by clicking... | stackexchange/codereview |
Below is some code I've put together to contol a siren for a fire service.
It works by webscraping a paging feed and looks for set triggers.
Is there a better way of doing my code or is this "pythonic" enough or can it be improved?
Im python self taught.
"""PYTHON SCRIPT TO CONTROL SIREN
This script will webscape a p... | stackexchange/codereview |
I have created a few extension methods to get the direct reports of a UserPrincipal as UserPrincipals themselves. This saves the user of the API quite a bit of typing.
public static IEnumerable<UserPrincipal> GetDirectReportUserPrincipals(
this UserPrincipal userPrincipal)
{
var directReportDistinguishedNames =... | stackexchange/codereview |
Took a shot at implementing std::shared_ptr, with a thread-safe refcount and weak count. Didn't do weak_ptr, I'm doing this for learning purposes, and I think from an educational standpoint there's not much to learn from adding it.
Also tried to implement the "we know where you live" optimization, with the control bloc... | stackexchange/codereview |
Motivation:
I am working with sequences of n-bit values coming from an ADC. I was initially using a std::vector<unsigned short> to store these values (12 bit in my case) but I wanted to improve on memory efficiency since this approach uses 16 bit per value instead of the 12 bit of information.
My main concern is disk u... | stackexchange/codereview |
Following is a very crisp solution for solving n-queens problem in Racket programming language. The method is to get all permutations (so that no 2 queens are in same line) and to check these for any of them being on diagonals:
#lang racket
; FOLLOWING FN RETURNS TRUE IF QUEENS ARE ON DIAGONALS:
(define (check-diagon... | stackexchange/codereview |
The problem is to find LCM of two numbers. I have tried to solve the problem in two ways. First by using the LCM formula :
LCM (a,b)= a*b/GCD(a,b).
Second, by finding out the multiples of each number and then finding the first common multiple.
Below are the codes that I have written:
Code 1:
#Using the LCM formula LC... | stackexchange/codereview |
Here is my implementation of John Conway's Game of Life in Python:
from copy import deepcopy
def countSurrounding(board, row, cell):
SURROUNDING = ((row - 1, cell - 1),
(row - 1, cell ),
(row - 1, cell + 1),
(row , cell - 1),
(row ... | stackexchange/codereview |
Does this function
automationStatusIsSuccessful = (data) ->
data.Automation.Status isnt "FAILED" and data.Automation.Status isnt "COMPLETEDWITHERROR"`
make the conditional statement more readable or less readable?
With:
automationStatusIsSuccessful = (data) ->
data.Automation.Status isnt "FAILED" and dat... | stackexchange/codereview |
I come from java background and I am trying to implement lambda chaining in Python. Below is my code
li = ["amol", "vikas", "rahul"]
li2 = list(filter(lambda n: (n == "Amol"), list(map(lambda name: (name.capitalize()), li))))
print(li2)
This Function will
Capitalize the names
Filter the names with "Amol"
Currently t... | stackexchange/codereview |
I made a merge sort and wanted to ask for code review. It passed all of the unit testing. The idea behind the classic Mergesort algorithm is to divide an array in half, sort each half, and merge the two halves into a single sorted list.
Examples:
merge_sort([2,7,5,9,8,9]) -> [2,5,7,8,9,9]
merge_sort()([7,1,8,2]) -> [1... | stackexchange/codereview |
I have started to learn C and decided to recreate my bakery task in C.
As I am new to the language, I am unsure if I have approached the task in the right way using structs. Feedback on the style of the code would also be appreciated.
#include <stdio.h>
double cup_ingredients[4] = {4.0,0.1,12.0,14.0}; // Amount of eac... | stackexchange/codereview |
I have recently developed a Java program for a simple Tic-Tac-Toe game and would like to request a code review to improve its quality and learn from experienced developers. Below is the code for my game:
Board.java
import java.util.Scanner;
public class Board {
private char [] [] board;
private final int SIZE;... | stackexchange/codereview |
I have created a scraper for yell.com in vba. The scraper is efficient enough to pull data from that site, whatever the search parameter is. If any link from that site is given to my parser, it is able to scrape the whole records irrespective of how many pages it has spread across. There is no "a" tag for the first pag... | stackexchange/codereview |
The task I'm doing is, fetch external API, then save the results to database.
I'm a beginner, I really wanna improve my code, to handle error well, and remove redundant code. The code is working, but I'm bit confused with promise and try-catch. I watched some tutorial, still not sure in the situation which way is bette... | stackexchange/codereview |
Mind that this is my first actual program in C++ and I tried to prepare for any possible input. Also the reason I included static_cast<void>(generator(range)) is to throw away the first random value because I read on LearnCpp.com that throwing away the first is a common practice to produce more random results. Anyway... | stackexchange/codereview |
I wrote a program (hard-code) in MIPS that gets an array of 10 integers and calculates the sum and the square sum of them.
The array is {23,-2,45,67,89,12,-100,0,120,6}
.data
array: .word 23,-2,45,67,89,12,-100,0,120,6 # array = {23,-2,45,67,89,12,-100,0,120,6}
length: .word 10 # the length of the array is 10
sum: .wo... | stackexchange/codereview |
I have a working function achieving what I want to do, but, I feel that there is a better, concise, and appropriate way to achieve this but I can't quite put my finger on how.
Given an object with (n) recipients, duplicate the message so that there is only ever one recipient and every recipient receives a unique messag... | stackexchange/codereview |
I have a cumulative transition matrix with probabilities for all the possible states from 1 to 5. Now the algorithm for simulating future states is following: the initial state is selected randomly, and a random value between 0 and 1 is then produced by uniform random number generator.To determine the next state in the... | stackexchange/codereview |
I am using the ancestry gem to organize my post categories tree.
I have 8 parent categories, and they all have many child categories.
To retrieve an array of child categories, I use:
parent_category.children
I defined these relations in my category model:
has_ancestry
has_many :posts
has_many :users, through: :... | stackexchange/codereview |
This is my rewrite of the program posted here, based on janos's comments. I also added the ability to read from stdin.
I've also included a test script. I wanted something lightweight I could easily re-run, but didn't want a dependency or full test framework like bats. Comments on the test script are also welcome.
N... | stackexchange/codereview |
This looks quite verbose to me, using the command substitution and echo:
# Source file
source=$( [[ ! -z "$1" ]] && echo "/home/$1" || echo '/root' )
source="$source"/.bash_history
[[ ! -f "$source" ]] && echo "History file '$source' not found." 1>&2 && exit 1;
# Am I dealing with root
isRoot=$([[ "$source" =~ ^/root ... | stackexchange/codereview |
After programming in Haskell for a while, I've gotten attached to a functional style. This is clearly evident in the code for my genetic algorithm.
Could you provide me with some hints as to how I can make this code more pythonic? By that, I mean provide some method of organisation rather than throwing a bunch of fu... | stackexchange/codereview |
I have some JavaScript that was put together for functionality but I wanted to know if there was a better way to write it. As it stands it's a little hard to read and follow.
$(document).ready(function(){
var loop = null;
$("li").click(function(){
$("li").css("box-shadow", "none");
$(".selector").css("visibili... | stackexchange/codereview |
I have written a file to extract text from news articles. The program works as I want it to except it takes hours for it to write the output files. I have tried different buffering options as well as adding the data I want written to an array before writing that to the file. I have almost no experience programming so I... | stackexchange/codereview |
I was given a task:
Given any integer - write a program, which:
finds all digits of the integer
writes odd and even digits from the integer
finds the biggest even and smallest odd digit
writes the biggest possible number that can be formed by rearranging the odd digits
writes the smallest possible number that can be ... | stackexchange/codereview |
Purpose
I've never implemented a DoublyLinkedList and thought it would be a good data structure exercise. I tried using outside
resources as little as possible. I also tried to keep things as simple as possible
Discussion
The DoublyLinkedList is made up of a Node head, a Node tail, and an int length. I did not generici... | stackexchange/codereview |
I have a code based on the following problem "Mapping phone numbers to names", the problem is that when they are going to process large data(+100.000) the program ends by timeout. my code and problem is this, how can I optimize my code to consume less time?
my code
function processData(input) {
var r=input.split(/\... | stackexchange/codereview |
I have implemented my code using Cython. It is the current bottleneck in my computations.
There are two non-numpy functions involved:
calculate_2D_dist_squared which calculates the distance squared between two points
calculate_2D_dist_squared_matrix which generates the distances squared between every two distinct vert... | stackexchange/codereview |
I decided to implement a simple smart pointer class in C++ name my_pointer. Please review this code.
#include <iostream>
using namespace std;
class my_pointer {
private:
int *data;
public:
explicit my_pointer(int *p = nullptr) : data(p) {}
int& operator *() {
return *data;
}
~my_pointer() {... | stackexchange/codereview |
I have input of a string containing a single number (like: \$3\$) or a range (like: \$1-5\$). Sample input, all together, looks like: "1-5,3,15-16", and sample output for that input looks like "1,2,3,4,5,15". Output doesn't need to be sorted.
I built something to parse this, but it's ugly. How can I improve this?
from ... | stackexchange/codereview |
This class simply allows you to use an enum while only allowing you to set a single flag. If multiple flags are set they will be rejected--unless the total of the combined flags is the same value of an existing flag. Such as Flag1 | Flag2 == Flag3 would be an example thereof.
C# 6.0:
public class RestrictedEnum<T> wher... | stackexchange/codereview |
In my app I'm using JSON Web Tokens for authentication purposes, using the pyjwt library. Instead of using static keys and/or worrying about key distribution, the server generates a public/private key pair upon startup itself and just keeps it in memory. The keys will be reset and thereby all existing tokens invalidate... | stackexchange/codereview |
I like to reuse code as much as possible and keeps things DRY. But I'm afraid that sometimes it creates too many layers of indirection. It then becomes a chore to find where code exists that is relevant to the problem at hand. I'll give a couple of examples.
In the first example, I'm using inheritance on classes that a... | stackexchange/codereview |
Task: Return true if a transaction is allowed and return false if transaction is prohibited.
Details:
1. String is represented as an "array" that can contain up to three elements.
We need to evaluate a charge against a list of rules and see if we can allow the transaction to happen.
Each rule (Allow or Deny) can cont... | stackexchange/codereview |
def triangularNumber(n):
if(n == 1):
return 1
else:
return triangularNumbers(n-1)+n
works great to find the nth triangular number up to 996...
I get some error in the recursion after 996. But can tell what it is because it just keeps running through the loop. Anyone see the error?
| stackexchange/codereview |
In a complex library I've been working on, I got pretty tired of all of the individual type functions and operators to determine whether I was working with an object or piece of data of a given type. This was especially true when I was checking for inherited prototypes between classes. In an effort to alleviate, I made... | stackexchange/codereview |
I'm writing this as an exercise. I would probably use a vector as a buffer internally (the extra capacity pointer overhead is not important enough). Primarily it's an exercise in writing copy/move constructors and assignment operators.
What are some of the pitfalls of defining these operators explicitly? What could go ... | stackexchange/codereview |
I am in need of a "debiased" clamp function, to generate a uniformly-distributed random number from a good PRNG.
Let's assume that RNG in the below code is a field containing an instance of a good (or good enough) PRNG such as PCG, Xoshiro, or MT, which produced a reasonably-uniform distribution of random integers.
pub... | stackexchange/codereview |
I have written a chess game. No castling or en passant, pawn gets promoted to queen. Game isn't drawn after 50 moves. The AI is a naive minimax implementation.
The chess AI algorithms can be improved, more tricks can be used. Alpha-beta pruning, negimax. But that is not my intent. My goal is not to make a great chess e... | stackexchange/codereview |
I'm fairly new to scripting in Python. I'm looking for suggestions on improving any of the following in the below script: my coding style, performance, readability, commenting, or anything else.
"""
META
Author: James Nicholson
Date: 8/16/2013
DESCRIPTION
This script takes a list of groups from a text file and creates... | stackexchange/codereview |
I have a data set.
public class EmployeeRepository
{
public static List<Employee> AllEmployees()
{
var loc1 = new List<Location> { new Location { City = "Gretna", State = "VA", ZipCode = "24587" }, new Location { City = "Charlotte", State = "NC", ZipCode = "28012" } };
var loc2 = new List<Locati... | stackexchange/codereview |
I have a circular buffer (array/first in first out), a consumer and a producer. A producer puts random numbers into the array, and a consumer takes the first number and checks if it is relative prime.
My code works, and I think it works correct, but I want to improve it.
I am not really sure about my "void run" methods... | stackexchange/codereview |
There is an updated version of this code with some of the recommended changes made here.
I have created an implementation of a multi-dimensional array which utilizes a single continuous memory buffer to improve cache locality. My intention is for this to behave in a similar way to a multi-dimensional vector in c++, and... | stackexchange/codereview |
I'm doing a college assignment with jQuery Mobile and JSON. Best practice with jQuery mobile is my main concern.
My html starts off with a main 'page' (data-role="page") inside a div with id="all-pages".
I use jQuery's .getJSON method to connect to a local JSON file called profiles.json. profiles.json contains an arra... | stackexchange/codereview |
This is an assignment for an intro to Java course. It works with the test case given, but I would like to know if there is anything / a lot of things that should be different or could be better.
Specification:
Write a Java application that accepts 5 “valid” numbers from the user.
A valid number is between 50 and 100 ... | stackexchange/codereview |
Based on the feedback I have got from the guys reviewing the code as posted in my previous question.
Create database connection and run the insert, delete, update queries class
I have used interfaces and wrote the following code
/* */
namespace SampleInterfaceT1
{
public interface IDbConSetup
{
DbConnection Open... | stackexchange/codereview |
Preface: I am learning Rust through the Advent of Code
The task is to read lines from a file, parse each as an integer, then provide a summation of all the numbers. My solution looks like this:
use std::fs::File;
use std::io::{self, prelude::*, BufReader};
fn main() -> io::Result<()> {
let file = File::open("day01... | stackexchange/codereview |
I wrote a simple android app to export the browsers history as JSON, but I do not know if the resulting JSON is a format that the user will easily be able to parse and use.
Is there any way that i could improve the resulting format? Will it be easy for the user to use?
I have the title of the page first, should I ... | stackexchange/codereview |
How efficient is this program? How could I make it more efficient?
package main;
import java.math.BigInteger;
public class Ackermann {
public static void main(String[] args) {
System.out.println(ack(BigInteger.valueOf(4),BigInteger.valueOf(2)));
}
public static BigInteger ack(BigInteger a, BigI... | stackexchange/codereview |
I've been working on a Java-based mathematics library focusing on vectors and matrices. I plan to use it for an important upcoming project, so the classes are analogous to data types available in GLSL (e.g. Vector2 for GLSL's vec2, Matrix4 for GLSL's mat4, and so on).
I'm trying to only expose interface to clients (e.g... | stackexchange/codereview |
Reviewing code doesn't necessarily require actually building it, but it's often helpful to do so in order to evaluate fully. I usually create a CMake project and build from there. Since we're all about code here, naturally, I decided to automate part of the process. Specifically, here's how to use this code:
Hit... | stackexchange/codereview |
This is a very simple concern, could somebody take a look at a few lines of my code? I'm writing a simple Java multi-user messenger, it is structured in a desktop client with a Swing GUI, a java server based on plain sockets and a service library holding general utilities... At the moment I transmit messages through a ... | stackexchange/codereview |
I'm very new to Python and would like some feedback on my script. I'm fairly clueless to best practices, code correctness etc. so if there's anything at all that looks wrong, isn't 'pythonic' or could be done in a simpler way, I'd love if you could point me in the right direction.
#!/usr/bin/env python
"""Follows Ins... | stackexchange/codereview |
The Unique Function is supposed to be able to replace std::function in most situations where you do not need to be able to copy the functions, just move them. This has the primary advantage of being able to take move-only function objects, including lambdas that have std::promise moved into them. It also features small... | stackexchange/codereview |
I'm creating a 2D tile based platformer with AABB (Axis aligned bounding boxes), and it works, I just want to organize and optimize my setup. Here are methods in my player class and entity class that are relevant to the collision. How could I make this better? I'm harshly looking at that public boolean[] method, but I ... | stackexchange/codereview |
I'm trying to pad a tensor of some shape such that the total memory used by the tensor is always a multiple of 512 E.g. Tensor shape 16x1x1x4 of type SI32 (Multiply by 4 to get total size)
The total elements are 16x4x1x1 = 64
Total Memory required 64x**4** = 256 (Not multiple of 512)
Padded shape would be 32x1x1x4 = 51... | stackexchange/codereview |
How does this look for basic image rotation? What is there to be improved here?
<p>
<img src='images/rotation/dsc_0052.jpg' id='rotateImg0' alt='image rotation' />
<img src='images/rotation/bilde1.jpg' id='rotateImg1' style='display:none;' alt='image rotation' />
<img src='images/rotation/bilde2.jpg' id='ro... | stackexchange/codereview |
This code is a chunk of big project, so I am sorry in advance for not adding everything as it's just not possible.
[DataContract]
public class Companionship
{
[DataMember]
public int ID;
[DataMember]
public string ClientID;
[DataMember]
public string UserSID;
[DataMember]
public string R... | stackexchange/codereview |
A few functions to let me manage TAGS files more easily. Typically, my projects contain at least one sub-folder. I got sick of manually updating, so I wrote this to help me update a single TAGS file per project (always in the projects' root directory).
Please share your thoughts (aside from "Why are you using Emacs?", ... | stackexchange/codereview |
Question
I feel like my code could be more elegant/more pythonic/faster, but I can't think of too much more to improve. So, I've come to the internet to see what more can be done with standard python.
What my code does
My code counts anagrams for each word in a list of words. For example:
post, spot stop, tops
are fou... | stackexchange/codereview |
I've written a backend for a chat app but I'm not sure, if I'm following all the SOLID principles and if my code is clean enough.
IModel interface for my db entities:
interface IModel
{
/**
* get a specific field from the model.
* @param string $fieldName name of the field to return
* @return mixed;
... | stackexchange/codereview |
I have written the following simple find function template that does a linear search.
#include <iterator>
#include <concepts>
#include <array>
#include <random>
#include <algorithm>
template <std::input_or_output_iterator InputIt, class T>
requires ( std::equality_comparable_with<std::iter_const_reference_t<InputIt>... | stackexchange/codereview |
Terminology usage: I will use chunk, page, partition, or subrange interchangeably.
I frequently use and promote using the System.Collections.Concurrent.Partitioner class (see link). For my particular usage, I always use it for a full indexed collection, i.e. IList<T>. Sometimes I may use it for single-threaded proces... | stackexchange/codereview |
####make the BLOSUM matrix into a class for easier retrieval
class BLOSUM62():
def __init__(self):
with open('BLOSUM62.txt') as f1:
entries = [(line.strip()).split() for line in f1.readlines()]
self.scoring_matrix = {(entry[0],entry[1]):int(entry[2]) for entry in entries}
def __... | stackexchange/codereview |
I am trying to convert a BLOB that is stored in a database to a JPG and then I need to display it on an html form in a C# application.
A little backstory first - this is an older web app that was designed to take a JPG (photo) that was stored as a path in the database, resize it, then show as a BLOB. This functionality... | stackexchange/codereview |
In this code, I'm overriding the sorter and matcher for Twitter-Bootstrap's Typeahead functionality. The reason for the override is to allow state (technically Jurisdiction) abbreviations to be used to match the full state name. I've reduced the length of the source array in this example for brevity, but a full version... | stackexchange/codereview |
This is the current very repetitive and long SQL I have. Unfortunately I'm not that good at SQL to group this and get rid of the repetition.
select * from Mail
where admin_status = 1
and admin_id = 4
and core_event_id =0
and user_id !=0
and mail_reply_status = 0
and sent_to = 0
and admin_inbox_date > DATE_SUB(CUR... | stackexchange/codereview |
I have a program which finds, well, a magic square of squares. The problem is, it's quite slow - it processes around 50 numbers in half a second when the number range is above 40,000.
Is there any way to improve this code?
from math import floor
# checksquare checks for the possibility of a set being a magic square.
... | stackexchange/codereview |
For a simple try at parallelization on my own outside of school, I've created a number factors calculator. I hope to eventually come up with something more creative.
Since I don't have access to parallel computers at this time, I'm using OpenMP provided by my compiler (gcc 4.8.1) and running it on my laptop (Intel Cor... | stackexchange/codereview |
The function below is designed to return a UTC offset string, in the form used widely by timestamps, of the user's current time for when only naive date time objects are available (no time zone information).
I've tested it on two systems, which are in different time zones, and it works perfectly. However I'd like confi... | stackexchange/codereview |
I want to convert a Version object to a string, but with the parts padded to a given width. E.g. 0.22.1 with parts padded to a width of 2 when converted to string would be "00.22.01"
A simple task, simple enough that I'm surprised it's not part of the class already. I'm not that used to .Net and it's string handling th... | stackexchange/codereview |
My code consists of Split, Mid, Left, Right and Replace functions which are used to trim my data into a more neat manner. However, it's too long and inefficient, it takes too much time to go through all this because I have up to thousands of files that will go through this.
My main code goes through a folder and goes t... | stackexchange/codereview |
I have this update method which decides whether to update or recreate(same as update but resets the approval_status and create_date) of the building_approval object. I have the on_progress? method on building_approval class to check whether it needs to be updated or recreated so no flags are being passed from the view,... | stackexchange/codereview |
I have an HTLP template file called "template.tmpl". In the template I have a few placeholders like {{NAME}} and {{USERNAME}}. I am then loading the template file into a variable called $template using file_get_contents. I then put the $template variable through a function which deals with replacing a series of placeho... | stackexchange/codereview |
This works, but it's huge.
We need to repeat each table column on each UNION SELECT, as well as the WHERE clause for DATE comparison.
(
SELECT GROUP_CONCAT(APA_T.district), t.name
FROM tbl_activity AS t
INNER JOIN tbl_activity_package AS ap ON t.id = ap.activity_id
INNER JOIN (
SELECT DISTINCT apa.district AS dist... | stackexchange/codereview |
awhile ago I asked about a thread pool implementation I had made. I took the advice down and modified it a lot over time to fit my needs. It has been serving me extremely well in all of my projects but I was wondering if there was anything else I could improve on?
Here is the class:
class ThreadPool{
public:
/* Co... | stackexchange/codereview |
Is this the best way to implement a genetic algorithm framework? I'm just a student and wanted to know if I can improve the code that I have done. Some of the code I copied from the framework documentation:
namespace xx.xx.xx {
class Program {
static GrafoDistrito grafo;
static int total;
... | stackexchange/codereview |
Basic idea (foo and foa are filenames):
using System;
using System.Collections.Generic;
using System.IO;
namespace FileIndexer
{
class FileIndexTrie
{
private class CachablePath
{
public string filename;
public int cachedPath;
//stolen from: https://stackov... | stackexchange/codereview |
I am a JavaScript programmer beginning with Go. I tried to replicate filter and map functions like JavaScript's, as an exercise.
Here is what I came up with.
The filter function:
func Filter(slice interface{}, cb func(i interface{}) bool) []interface{}{
sliceValues := reflect.ValueOf(slice)
newSlice := []interface{}{}... | stackexchange/codereview |
I was seeing alot of machine learning applications calculate fitness via 1.0 / x. Division in computers is slow so I came up with a version that is about ~36% fast on my architecture (-march=x86-64).
#include <cmath> //std::exp2, std::log
#include <numbers> //std::numbers::log2e
#include <stdlib.h> //rand, srand
#i... | stackexchange/codereview |
I feel like I don't understand how polymorphism works in Python. Here is something I put together.
class _Tag(object):
def __init__(self):
#DisjointedTag and JoinedTag will bypass __init__.
#Also, self will not be defined within this class.
#Bottom line, this class is just for inheritance.
... | stackexchange/codereview |
This is an answer to this SO question: Vba comparing 2 columns of data.
In that question the OP code is very slow (also not working properly but the problem is fixed)
I spent some time to implement a version with decent performance at 1M rows+
Note: I know Activesheet is discouraged (and I avoid it) but the Sub is q... | stackexchange/codereview |
I'm currently writing a game of life with small extra features but I ran into a problem - in my first try i decided to use simple list of Cell objects:
class Cell:
def __init__(self, x, y, is_alive):
self.is_alive = is_alive
self.x = x
self.y = y
self.will_be_alive = False
se... | stackexchange/codereview |
I wanted feedback/review on my implementation of a selection sort in c++ (for ints only, no templates). This is my first attempt in c++ making anything beyond simple projects/hello world!
Q: Should my for loops use uniform initialization like for(int i { 0 }; ... ?
Q: Should everything else use uniform initialization l... | stackexchange/codereview |
I am aware that there are other ways of implementing a priority queue e.g. using a sorted array/list. Would appreciate some comments on my implementation of a basic priority queue supporting three simple operations: Insert, Min, Max
public class QueueEntry<TKey, TValue> : IComparable<QueueEntry<TKey, TValue>> where TKe... | stackexchange/codereview |
I am making a hobby OS, and I thought about adding a command for interactively rendering the Mandelbrot set. The "interactive" part is not really important, but I wanted to check if the Mandelbrot algorithm is as good as it can be.
The most performance-sensitive part is the code inside the inner for loop, the one that ... | stackexchange/codereview |
I want to have a function that checks to see if a certain resource (deployment, job, cronjob etc) exist in a namespace. Using the Kubernetes Python client, I can create a boolean function (using deployments as a concrete example).
from kubernetes import client, config
def deployment_exists(name, namespace="default"):
... | stackexchange/codereview |
I have getOffseSeconds method:
private int getOffsetSeconds(LocalDateTime localDateTime, ZoneId zoneId) {
return ZonedDateTime.of(localDateTime, zoneId).getOffset().getTotalSeconds();
}
This method is used in shifted LocalDateTime calculation
private void shiftEventDateTimeToOriginalZone(EventDto event) {
even... | stackexchange/codereview |
I am writing a specialized version of the cross correlation function as used in neuroscience. The function below is supposed to take a time series data and ask how many of its values fall in specified bins. My function xcorr works but is horrifically slow even. A test data set with 1000 points (and so 0.5*(1000*999) in... | stackexchange/codereview |
Background
I am re-writing a series of algorithms together with a colleague that we are going to later on publish in a packet for the community.
To start, I picked the typical bubble sort algorithm.
Objectives
The function must be pure
It must be efficient
It must obey the complexities listed in https://en.wikipedia... | stackexchange/codereview |
I was wondering how efficient my code is creating custom indexOf for strings in JavaScript using regex instead of looping with a for statement the whole way in most solution I find and I believe this got \$O(1)\$ since no loop is needed.
The idea is to use regex that put either the key or any list of word that is not k... | stackexchange/codereview |
What the code does short version: Given your hints for Wordle, narrows down the list of potential matches and returns them as a list.
Slightly longer version: It takes the positions and values of your green clues, positions and values of your yellow clues, and all your gray clues and creates a regular expression to fil... | stackexchange/codereview |
So I saw a need for and came up with a class implementation to group constants, which I'm calling a Constant Class. I wondered if there existed other similar implementations or if there is a flaw in what I'm doing. My team is currently finding it fairly useful and thought we should see what other people thought. Also t... | stackexchange/codereview |
VSDiagnostic's latest refactoring and code fix detects when a switch does not contain case statements for each of the enum members and adds any missing members. So, for example, with the following enum and switch, VSDiagnostics will detect that some members are missing and add them as shown in the second switch:
enum... | stackexchange/codereview |
The code is supposed to group start and end time logs and provide log counts and unique ID counts. The grouping will be variable 1 hour, 6 hours, 12 hours, 24 hours, etc.
What is the better way to rewrite the simpler version for this code?
Input: No of day reamins 'x' in inputs.
import pandas as pd
fn = r'Dart.csv'
... | stackexchange/codereview |
You can call it ports and adapters or hexagonal architecture. Regardless, what's facinated me about this picture isn't the layers. It's the Clean Architecture UML diagram over in the corner of a plugin that looks like an upside down, folded over version of the Dependency Inversion Principle:
So while the original DI... | stackexchange/codereview |
I read about debounce this morning and ended up needing something similar to the concept in real life this evening to build a poll that checks whether a link I receive from an async call is ready to be used in a href element.
But what I'm asking for are
highlights of the risk to my implementation,
to learn if there ar... | stackexchange/codereview |
How can this algorithm be improved? I mean, a list with 3000 items takes about 5 seconds to sort, according to Sublime Text. Using Python's sorted function is immediate.
from random import randint
def bubble_sort(iterable):
while True:
corrected = False
for item in range(0, len(iterable) - 1):
... | stackexchange/codereview |
I have two admin groups - VCS, and VPN. For each group, I need to get the list of all the people in that group, along with their IDs.
What is the best way to do this? Could you please suggest if it is good enough?
Also, should I use a map to store the data instead of creating a new object GetAdminInfo?
public class Ge... | stackexchange/codereview |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.