instruction stringlengths 71 95.1k |
|---|
I'm using the
Bogus for .NET: C#, F#, and VB.NET library.
What would be a more efficient way to generate a list of unique random longs?
public IEnumerable<long> GenerateRandomNumbers(int count = 1)
{
var f = new Faker();
List<long> temporaryList = new List<long>();
for (int i = 0; i <... |
Context
I am following this tutorial .
My mission is to convert an English sentence to a German sentence using Bahdanau Attention.
Summary of the Code
I first took the whole English and German sentence in input_english_sent and input_german_sent respectively. Applied an Embedding Layer on both of them. Passed the input... |
I've been trying out React for a couple of days and I tried to build a button component with some conditionals. Everything works but I feel like I am not doing it the right way.
Could anyone review my code and give me some advice and tell me what I am doing wrong or what i could do better. I think I am using too many r... |
Sometimes you need to do things when a condition changes, here is a simple class to keep track of the state of the last call and execute callbacks when the state changes.
#include <functional>
#include <cassert>
/// latch is a class that contains of a test function and a couple of callbacks, when the return
/// valu... |
This is a follow-up question for A TransformAll Function For Various Type Arbitrary Nested Iterable Implementation in C++. The following code is the improved version based on G. Sliepen's answer. In order to match the conventions of the STL, the function named recursive_transform here uses the is_iterable concept and t... |
Anyone here who uses Python for solving bioinformatics problems. This is the code I have written for counting the number of k-mers like monomers, dimers to hexamers from the fasta file. You just have to give the ncbi accession number for the fasta sequence and then it counts the number of k-mers. If you've time, please... |
I have some data being returned to me in the form of a deeply nested Dict and I need to parse multiple values from it which may or may not be there. I saw the dpath library and tried to come up with a simplified version that fits into one function.
I think it's pretty good but I'm wondering if I missed something or the... |
I'm posting two solutions for LeetCode's "Defanging an IP Address". If you'd like to review, please do. Thank you!
Problem
Given a valid (IPv4) IP address, return a defanged version of that IP address.
A defanged IP address replaces every period "." with "[.]".
Example 1:
Input: address = "1.1.1.1"
Output: "1[.]1[.]1[.... |
Goal
To determine the coordinates of some signal source in a 3D space, given the coordinates of four observers and the time at which each saw the signal, as well as the velocity of the signal.
Algorithm
The algorithm is more-or-less comprised of two pieces: the approximation search algorithm, and the localization algor... |
Context
I was solving a task on CodeSignal here
You can view the task on the link I provided above.
I have also put the task at the bottom of the post.
Code
def check(matrix, num):
for arr in matrix:
for number in arr:
if number != num:
return True
return False
def spiralNu... |
These extensions create an IObservable<T> that creates a long running task that can be cancelled. It runs the Func<T> after each interval of time and passes the result to OnNext() until the task is ended by the CancellationToken. The important thing here is that only one task is created with one loop. I'd prefer to use... |
I've written the following function to produce n realizations of a CIR process for a given set of parameters:
def cir_simulations(alpha, mu, sigma, delta_t, n, num_sims):
x = np.reshape(np.array([mu] * num_sims), (-1, 1))
for i in range(0, n):
x = np.concatenate((x, np.reshape(x[:, -1], (-1, 1)) + alp... |
Update: link to corresponding release
The code presented here is tagged as release version v0.1.0 on Github for easy reference.
Introduction
bump is a command-line utility that I use to "bump" up the semantic version numbers present in any text file. It is written entirely in C and doesn't use malloc anywhere. Here's a... |
This is the follow-up question for A recursive_transform Function For Various Type Nested Iterable With std::variant Implementation in C++. As G. Sliepen's answer mentioned, leaving only recursively transforming operation for recursive_transform() may be a better idea. As the result, the implementation of recursive_tra... |
CodeReview Community! I was hoping you'd be able to review my basic OOP program. Last year I did a strictly procedural one and now I’ve incorporated OOP techniques. Ignore the commented out piece of code. The Hungarian Notation is a requirement for my university course so please don’t criticise the fact I’ve used it. I... |
Recently I thought about what a program would look like if all its characters that could become trigraphs became trigraphs. For example
int main(void)
{
int array[10];
}
would become
int main(void)
??<
int array??(10??);
??>
As a result I decided to make a program using ANSI C89 that takes a file in and conv... |
Autodidact and inspired by David Beazley code (to improve my skills in Python) i would like to get your feed back on this Parser code.
NB: The lazy property let the code be computed only one time if used (https://github.com/dabeaz/python-cookbook/blob/master/src/8/lazily_computed_attributes/example1.py)
class lazypro... |
TL;DR
I'm wondering how to organise test functions using mocks for GoLang drier & easier to follow.
Function
I have a template function that is very similar to ACF's getField:
It take's in a string (field name) & the post ID.
It checks if the ID exists and the obtains the post by ID (the f.store.Posts belongs to the f... |
Recently I had a python test and, unfortunately, I failed. I'm going to re-do my test and the teacher gave me the tip to work more efficiently and clean. To practice this I made a blackjack game about 2 weeks ago with python and sent it to him to check. he has yet responded and my test is next week.
Can anyone take a l... |
Well, my intention here is to allow users to execute Unity methods/properties in other threads by using this Dispatcher implementation:
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Threading.Tasks;
... |
A dataframe and a right-sided formula are given:
dat <- data.frame(
A = c("a", "b", "c"),
B = c("x", "y", "z"),
NotUsed = c(1, 2, 3)
)
frml <- ~ A + B + A:B
From them, I want to get this list:
# [[1]]
# [1] a b c
# Levels: a b c
#
# [[2]]
# [1] x y z
# Levels: x y z
#
# [[3]]
# [1] a:x b:y c:z
# Levels: a:x b... |
In order to improve the performance of this code fragment, I have speeded up some code fragments by using the numba. However, a frustrating thing is that the performance of this decision tree is bad. For example, in the below code fragment, the performance of the decision tree is nearly 70 times slower than the impleme... |
Basically, the server gives me a token object. I am planning to check the token on the client if it is expired/valid before making a request to the server.
The function below works as expected. I just want to know if my code catch-all edge cases? I don't want, even 1 second that will request will fail due to an expired... |
I am learning C++ programming and just learned about basic OOP and decided to create a simple project to test my understanding and practice what I've learned. The idea I came up with is an event tracking system where you add events into a calendar and then you get all of your events displayed. I have 2 classes: Event, ... |
I've found my app, which uses the SortedList, has a poor performance.
So I decided to try to improve the performance of my app.
I created the FastSortedList class which I think is faster than the original one.
public class FastSortedList<TKey, TValue>
{
IComparer<TKey> _comparer;
List<KeyValuePair<TKey, TValue>... |
This is the follow-up question for A recursive_transform Function For Various Type Nested Iterable With std::variant Implementation in C++ and A get_from_variant function in C++. Thanks to G. Sliepen and Quuxplusone provide detailed review suggestions. However, the existed version of recursive_transform function assume... |
I'm a beginner in Django3 and just wrote an overview function to pass on some data to the template in a context variable.
I am definitely passing a lot more than I should as I only need only a few fields from each of these variables. Also, it might not be the most Django-esque way of doing things as it isn't using Gene... |
The purpose of this project is to generate an interactive logistic map. The user can click on the produced picture to magnify the picture at that point.
Here is the logistic map equation:
Here is my program:
public class LogisticMap {
public static double returnLogisticEquation(double x, double r) {
return... |
I was trying to figure out this problem, and I did. However, my code is so abhorrently ugly that I want to tear out my eyeballs when I look at it:
with open("gymnastics.in", "r") as fin:
rounds, cows = [int(i) for i in fin.readline().split()]
nums = [tuple(map(int, line.split())) for line in fin]
def populatePairs... |
I wrote a script that parses API on schedule (Tuesday-Saturday), downloading everything for the previous day.
import requests
import pandas as pd
from datetime import date, timedelta
# # This is what I'd normally use, but since there would be no data today,
# # I assign specific date myself
# DATE = (date.today() -... |
This is a problem from CodeSignal which can be founded over here
Here is an image on what we have to do:
Code
def map(cell):
new_cell1 = ''
for i in cell:
if i == 'a':
new_cell1 += '1'
if i == 'b':
new_cell1 += '2'
if i == 'c':
new_cell1 += '3'
... |
This is my first C program that is not "Hello World" level; I would welcome ideas to make it more efficient and readable.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <stdbool.h>
#define FALSE 0
#define TRUE 1
bool incircle(double x, double y);
int main (int argc, char *a... |
I created a simple guessing game where the player can choose whether the player is guessing the number or the computer.
If the player is guessing the number, then the computer will generate a random number between 1 to 100. Then, the player must guess the computer's number.
First, the player will type their guessed num... |
I have surrounded my initials with a circle. This is intended to be a re-usable component in a responsive layout. (When it is re-used the text will always be two letters, and the font won't change. It behaves sensibly when the browser zooms in and out, but I haven't yet considered if a different component size is neede... |
I am building a doctor appointment app with Django and Django Rest Framework. The app will have the functionality for secretaries to add appointments to a Doctor's calendar, and each Doctor may have more than one clinic (and multiple secretaries).
I built this Calendar Model to store the availability information of a d... |
I have put together a blogging application with Express, EJS and MongoDB.
There is a public, front-end part and a dashboard. In index.js I have:
// Bring the Dashboard
const dashboardRoute = require("./routes/admin/dashboard");
// Register Dashboard Routes
app.use('/dashboard', dashboardRoute);
// Bring the Posts Rou... |
I have a big python data-frame and I am trying to add a column to it with average number of missing values by row. I have inherited some code that is working but I'd like to reduce memory usage by removing intermediary values.
Here is a toy exemple :
students = [ ('jack', np.NaN, 'Sydeny' , 'Australia') ,
... |
This program takes text input and evaluates the expression.
This is meant to be an exercise.
I reinvented a stack class though I know C++ provides one in the standard library but it isn"t meant for production use but to solidify my knowledge on linked list data structure
I also made an infix postfix converter which con... |
This is a follow-up question for A recursive_transform for std::vector with various return type. Thanks to G. Sliepen provide further review suggestions. After digging into the topic of achieving a more generic recursive_transform function in both various output type and various container type, I still have no simple s... |
This is my prime sieve based on the Sieve of Eratosthenes.
import itertools
sieve = itertools.count(2)
primes = []
nprime = 0
for _ in range(10000):
nprime = next(sieve)
primes.append(nprime)
sieve = filter(eval(f"lambda x: x % {nprime} != 0"), sieve)
On my computer this code takes 13.4 seconds to generate... |
Bit of a pointless program (at the moment). It's intended more as practice for myself rather than anything else.
General idea is that you add details of a particular cat or dog, and it'll update a TreeView. A dog or cat can then be removed based on their assigned number.
Many thing I wasn't too sure on when creating t... |
I am working on an application that is required to be constantly running, and as a requirement should make multiple attempts for particular processes such as web API/database calls, just in case network connectivity goes down for a moment, or something similar.
In this case, I'm constantly having to write a basic algor... |
I want to organize mapping for my Angular app so that code structure would clear for other developers and I want to have as less code as possible.
I have an api service that is responsible for communicating with API. I create separate data services, which utilize the api service, to get backend data. The same data can ... |
https://leetcode.com/problems/number-of-enclaves/
Given a 2D array A, each cell is 0 (representing sea) or 1 (representing land)
A move consists of walking from one land square 4-directionally to another land square, or off the boundary of the grid.
Return the number of land squares in the grid for which we cannot walk... |
This is an exercise to implement a waiting room for an hospital with the following requirements:
Add (and remove) a patient to the queue of the waiting room
Move a patient up and down the queue
Show all patients in the queue
The queue needs to be persisted
The WaitingRoom interface:
public interface WaitingRoom {
... |
I wrote this code and I just can't stomach it.
The idea is that there is a schema, and the goal is to find the entry with autoIncrement set to true. If it's not found, the result should be idProperty.
const idProperty = 'id'
const schema = {
id: { type: 'number' },
code: { type: 'number', autoIncrement: true },
e... |
Hello I have writtern this Prolog code to solve a scrambled 2x2 rubiks cube. Also known as a a pocket cube.
%the cube is represented as a fact with 24 arguments,
%where each argument represents the color of the sticker at that position.
%The Positions are according to cube_diagram.png
%Test scrambles:
%G_scramble := c... |
I have code for a 64-bit timer register which can take in a 32-bit slice and depending on the inputs, place the slice in the high side or the low side, or increment the counter.
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;
entity CSR_TIMER is
Port ( clk : in STD_LOGIC;
reset: in ... |
https://www.hackerrank.com/challenges/queens-attack-2/problem
A queen is standing on an nxn chessboard. The chessboard's rows are numbered from 1 to n, going from bottom to top; its columns are numbered from 1 to n, going from left to right. Each square on the board is denoted by a tuple, (r,c), describing the row, r, ... |
I am writing a script to read rows (records) from an excel file with xlrd package and then create a dictionary for each row. In next step, I append each dictionary to a list. After I finished reading rows from excel file and prepared the list of dictionaries; I use odoorpc to connect to the interface of an Odoo applica... |
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <omp.h>
#define MAXN 10*1000*1000
int fillarray(unsigned maxn, int *p, int psize) {
int i, top = 1;
int n;
p[0] = 3;
printf(" 2\n 3\n");
for (n = 5;; n += 2)
for (i = 0; n % p[i] != 0; i++)
if (p[i] * p[i] > ... |
I'm creating a ticket reservation system in Java, I want to use a Two-dimensional String array for managing the seats. I have enums that hold the plane model and the amount of seats available so the array pulls the rows and columns from there. I just want to see efficient my code is and how can I improve it.
public... |
I am new to rust and I wrote a little program that takes a part CSS selector and returns the name of the element and two vectors containing its attributes (classes, ids)
Example
div#menu.big.pink => "div", ["menu'], ["big", "pink"]
Because I am new to rust I am looking for improvement to make this code better - more ... |
This is a follow-up question for A recursive_transform for std::vector with various return type and A recursive_transform for std::array with various return type. Based on these discussion about the recursive things, the another idea comes up in my mind that trying to implement a print function for arbitrary nested ite... |
I'm writing a spigot plugin where I give the user the possibility to send a message to the admins of the server. One of the requirements is that the coordinates of the player are stored, when the message is sent, and that it is stored in a sql table, so that admins on multiple spigot servers can access them independent... |
I recently came across a problem scheduling Coronavirus testing at a hospital; the testing capacity needed to be allocated to:
High risk wards (combining many factors).
Ones which hadn't been tested recently.
This presents a really tricky problem when scheduling, because as well as complexity in combining many proper... |
Reversi Game:
The image from the Reversi game:
I have my algorithm to find all legal moves in Reversi game.
Here's the code with comments:
"""
-1 => no disc
0/1 => player's disc
"""
for row_idx, row in enumerate(board):
for column_idx, column in enumerate(board):
if board[row_idx][column_idx] == -1:
... |
The code should do the following in order:
It should download/clone the public Github repository locally.
It should remove all the git history (and branches)
Use the Github API to create a new Github repository initialized with the input github repository content that you downloaded locally. The new repository should ... |
I'm learning MVP for Android and am wondering if that piece of code that I wrote is correct in terms of this pattern or maybe is completely messed up.
I'm wondering if there can be return type other than void in contract interface like I have in Model interface, secondly context shouldn't be passed in constructor of pr... |
My game engine uses the following broadphase collision detection algorithm:
internal void SweepAndPrune()
{
// First: order all objects from left to right on the x-axis:
IOrderedEnumerable<GameObject> axisList = _gameObjects.OrderBy(x => x.LeftRightMost.X);
// loop through all objects:
for(int i = 0; i... |
This is meant to be a performance-centric question as this type of conversion is obviously very common. I'm wondering about the possibilities for making this process faster.
I have a program that creates several thousand QR codes from a list, embeds them in an MS Word docx template, and then converts the docx files to ... |
The excercise is to print n nested squares. The nested squares are given as input by the user.
Example output for n = 4:
┌────────────────────────────────┐
│ ┌────────────────────────┐ │
│ │ ┌────────────────┐ │ │
│ │ │ ┌────────┐ │ │ │
│ │ │ │ │ │ │ │
│ │ │ │ │ ... |
I would like your opinion on my Remove-Files PowerShell function. It is used in my File-Removal-PowerShell-Script. It is designed to be very flexible so a script user can have configure it to remove files in multiple and various way as it often the chase.
Remove-Files function
function Remove-Files {
[CmdletBinding... |
I have recently finished my first real C++ program. It is text based, but hey, what d'ya expect out of a student? So, I would like person(s) to review the code I have written. It ain't short, but I wouldn't call it a "long" program either.
I couldn't figure if I could attach a file or not, so I provide a link, and if y... |
Background
I've been looking into a few different way to implement error reporting for an embedded system in C and there a couple things that I'd like to incorporate:
A generic and extensible error type.
Backward compatibility with OK and ERROR returns (i.e. can effectively return 0 or 1).
Well defined error codes on ... |
I put together some functions that allows a PHP script to send the SQL data obtained from user inputs on a website via an email attachment as a CSV file. It works perfectly and I have no issues with the code. Alternatively with the right SQL query it would run every X amount of days with a cron job and only produce the... |
Description
This is a simple "demo" app designed to help gain familiarity with interacting with an Sqlite database from C#, particularly storing images as blobs. The database has a single table, Contacts, represented by the following table creation SQL:
CREATE TABLE "Contacts" (
"id" INTEGER NOT NULL,
"name"... |
I am trying to do multiple queries in one call, so I organized my code as below:
try{
$query = $this->conn->begin_transaction();
$query = $this->conn->prepare("INSERT INTO table1(xx, xxx, xxxx, xxxxx, xxxxxx, xxxxxxx, xxxxxxxx, xxxxxxxxx, xxxxxxxxxx, xxxxxxxxxxx, xxxxxxxxxxx)
VALUES (?, ?, ?, ?, ?, ?,... |
I'm willing to check an an object's values in typescript, based on another object's keys.
The mental model is "the key exists, it's not an object, is the value in obj set, otherwise, it's an object, iterate again".
What would be your recommandations about this simple snippet :
/**
* Returns an array. If the array is e... |
I have recently started learning Java and decided to make a basic MDAS calculator in Swing. I am not completely new to programming but I may be making some common mistakes, or not writing the most efficient code.
I wanted to make a calculator that can take multiple numbers and operations before finding the answer using... |
The prompt is as follows: This script will use a text menu to give the
user options. The options will include the ability to add grades of different types as well
as an option to print the current grades and average. Types of grades are tests, quizzes,
and assignments. For the final average, the tests and assignments c... |
As I asked a question here, I want to write a python code for the following problem:
A person provides a service and he/she can serve \$k\$ clients each minute. Now, client number \$i\$ comes at the beginning of minute \$ a_{i} \$ and waits \$w_{i}\$ minutes to receive the service and if they don't receive the service ... |
I decided to implement a DisjointSet<T> data structure myself in Rust, with no dependencies except for std, for the challenge and to get better at Rust. I wanted to have as few requirements for T as possible, especially not T: Copy. I also wanted to be able to iterate over subsets easily.
use std::{
cell::RefCell,
... |
I have the algorithm which splits DateTime range into multiple ranges based on night time range.
For example:
Night start: 22:00, Night end: 06:00
Start time: 2020-10-26 21:00:00 End time: 2020-10-27 07:00:00
Expected output:
2020-10-26 21:00:00 - 2020-10-26 22:00:00
2020-10-26 22:00:00 - 2020-10-27 06:00:00
2020-10-2... |
I am to preview where a new element will be added on button click. I thought about just creating the element and showing that in the preview, but I have several buttons and some of the elements they create require input (via window.prompt) so I decided to just make a placeholder div and use that instead
Javascript:
var... |
I'm working on a spigot plugin, that deals with messages to from players on a server to the admin's. It's the same plugin this question relates to: SQL structure to save coordinates for spigot plugin . I've got a command, which allowes access to the inbox, and does all kinds of operations on the data. One of these oper... |
Seeing as a concurrent collection does not exist in .net that allows specific items to be removed, I have put together the following class.
It's important to note that it is only threadsafe until the LockTimeout on a given operation expires.
The main goal was to to guard against cheeky 'InvalidOperationException: Colle... |
I have written Python code which uses multiple if conditions and a for loop. The main objective of the code is to produce a traffic light system based on certain conditions.
Red = -1
Yellow = 0
Green = 1
It takes 4 months (m0, m1, m2, m3) and dataframe as an input, runs the condition through each row, and returns -1, ... |
I've been thinking about it for a while and, after asking a question on vi.stackexchange, I decided to write a small plugin myself and put it on GitHub; basically it offers a mapping to activate a kind of "window movement" mode where Vim waits for inputs that it appends to Ctrl+w, so that one does not have to press thi... |
I tried to implement a singly linked list myself, sorry it is not commented but I think it should be pretty self-explanatory, if not feel free to comment. I know that using namespace std; is not optimal, but I figured it would be okay for this little example. Same goes for defining the class right in the main.cpp file ... |
I am trying to improved my coding skills. I mainly work in web development. I had a "system" that I use in all my projects to fetch data from my DB to the browser. I tried an implementation of OOP, it works fine, but I dont think I did it correctly.
How can I optimized this code to make full use of an OOP design?
<?php... |
answer = input("what's the word")
answer_list = list(answer) #list version of the original word
presentation = []
for i in range(len(answer_list)):
presentation.append("_") #makes a list that shows the progress of the player during the game
incorrect = 0 #number of allowed guesses
completion = False # condition fo... |
I have a working program that reads user input keys and echoes them back to the screen using the producer/consumer paradigm (the project requires you to use threads).
While this program does work, it is unfortunately very inefficient. When I run the 'top' command, the CPU usage is over 200. Any suggestions to modify th... |
I am writing code that runs a simulation in an interactive way. The building blocks are:
runStep :: I -> State S O
runWorld :: World m -> O -> StateT W m I
Note that the world has some state W but is also allowed to have effects of type m. My question is about the function that feeds runStep and runWorld into each oth... |
This is a follow-up question for
A Summation Function For Arbitrary Nested Vector Implementation In C++ and A Summation Function For Various Type Arbitrary Nested Iterable Implementation in C++. I am trying to implement a recursive_sum function for the Boost Multidimensional Array Library. The purpose of this recursive... |
Here is method to calculate age given the birth date in the format YYYYMMDD.
function getAge(dateString) {
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && ... |
I have created a script where I add a timestamp to each value that has been found with a code that I have written:
import random
from datetime import datetime, timedelta
from typing import Dict, List
import time
class RequestFilter:
"""Tracks requests and filters them to prevent hammering."""
def __init__(sel... |
I'm making a game. There is a turtle and lots of platforms it can walk on. It walks on its own and you can change the direction it is walking. I implemented a working logic, but I think it can be improved.
I made 2 classes (one for the turtle and one for the platforms).
class Turtle
{
public Rect HitBox;
public... |
I'm trying to make some methods more reusable and have now three classes that work together: AbstractDao (the superclass), MemberDao (extends AbstractDao) and ProjectTaskDao (extendsAbstractDao). The method insert is very similar in both subclasses with some minor differences:
insert method in MemberDao:
public void in... |
I have some piece of code that I already optimized, however I found that there is an edge case that I should handle and I am unable to make it elegant.
char* data = get_data_from_queue(data);
Album album;
get_album(data, &album);
if (get_album_vals(album) <= 0) {
printf("Album doesn't exist, will try to create it")... |
I have rows in a database table with a hierarchypath column. The values in the column are hierarchy paths with up to four levels:
HIERARCHYPATH
---------------------------------------------------
FACILITIES \ FIREHALL \ PLUMBING
FACILITIES \ PARK
ROADS \ GRASS/TURF BLVD MAINTENANCE
ROADS \ SIDEWALKS \ REPLACEMENT
FACI... |
I've made a simple winhttp client in C++ and here is kind've the skeleton of the header file. I was thinking of initializing the session once and then using it throughout the rest of my http client structure. I don't know if this is super stupid but this was my thinking. This is just a skeleton of what I would like it ... |
For one of my labs I need to write a complete java program which will simulate a "very simple" dice betting game. The specifications are as follows: simulate the throw of 3 dice. If you throw three sixes then you win $20; if you throw three of any other value then you win $10; if you throw two dice which are the same v... |
I've made this program here (~240 lines) in which the user has to match their RGB Panel(right) with a randomized color on the left. It's a pretty fun program, and I suggest you try it out! It's fully runnable as is.
But a lot of the code seems repetitive and I was wondering how it could be condensed and made any more e... |
I'm working with a REST service that responds with indeterminate types. In particular, it can respond with a String, a correct payload (T: Decodable) or an error payload (PayloadError).
In order to cope with this type of requirement I've ended up with the following solution:
do {
let decoder = JSONDecoder()
let... |
Can I reduce the loop inside my method with map or is there a shorter implementation of this code that's dropping elements in sequence?
// Method that drops one element in sequence
def drop_Val_In_List[String](ls: Seq[String], value: String): Seq[String] = {
val index = ls.indexOf(value) //index is -1 if there i... |
Let's say you are living in a controlled economy where there is a baker in town, and every day he bakes a random number of loaves of bread (sometimes the oven breaks, or he has less ingredients). The people in the town queue up to buy a loaf of bread (you can only buy one loaf) based on a pre-assigned ticketing system.... |
This is a follow-up question for A Summation Function For Boost.MultiArray in C++. Besides the summation operation of all elements, I am trying to focus on the element-wise operation here. The main idea of this question is to implement an element_wise_add function for Boost.MultiArray. The purpose of this element_wise_... |
Can someone look over my code and clean it up?
I am trying to make a calculator with multiple inputs to add up. This is a snippet of the code that just needs to be cleaned up and shortened and I am relatively new to python so if anyone wants to clean this up thank you.
#functions
def x():
#needed for the the loop l... |
I recently created an intermediate calculator program, primarily to practice programming in C# but also for use with my college subjects. Any feedback on coding practices I can implement to optimise this program and any other programs I write in the future would be greatly appreciated.
Thanks.
using System;
namespace ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.