instruction stringlengths 71 95.1k |
|---|
Firstly, here is the relevant code. It is written in kotlin.
package com.minz.tournaments
import kotlin.math.ceil
import kotlin.math.log2
import kotlin.math.pow
@OptIn(ExperimentalStdlibApi::class)
class TournamentTree(initialParticipants: Map<Int, Participant>) {
private var rootNode: ParticipantNode
private val par... |
I am trying to convert objects inside an object(arbitrary objects) to Json and later retrieve it. I have developed some codes and would like to share if there is any problem in the code.
import json
Here is the first class
class Foo():
def __init__(self,x,y,bar):
self.x =x
self.y = y
self.b... |
My goal is to make a very simple library with the authentications basics: create a user and save its hashed password, change its password, have a method to check if the password is correct for login.
The usage I thought (you find everything in my Github repository), is this:
var cs = "Data Source=localhost\\SQLExpress;... |
This code finds which "secure file erase" command exists on the system. It used to simply test for "shred" and pick "rm" as a default. Now it is a bit more complex since I've ported the code to operating systems with "srm" and "rm -P". Is this still cleanly written? How can I improve it?
var shredPath, shredFlag st... |
This script was previously reviewed here: Part 1: Create or update record via HTTP request
I've made the changes that were suggested by @Reinderien.
Now that the code has been significantly refactored, are there any other improvements that could be made?
Description:
I have an external system that sends an HTTP reques... |
I have an api endpoint that, when called, initiates the generation of a report. This is time consuming process and response could come pretty late. So, we came up with caching architecture and once finished the response is saved to redis.
However, on the frontend side we dicided to make a request once in a while, until... |
I had a need to build a standardized layout for content on many of the pages of my website based on data returned from my web service but the project I'm doing this on is already bloated with stuff from previous developers and since I don't know what I can take out without destroying functionality, I needed a way to do... |
I've written a little program that I need for fixing two problems in my spherical panorama images.
It does two things:
If the image does overlap horizontally, it cuts away the overlapping pixels from the right side.
It fills up the image vertically with black, so that it has a ratio of 2 to 1.
I'm not too experienced... |
Having coded in Objected-Oriented style my entire programming career, it's hard to adapt to functional style fully.
I implemented a simple Hangman game:
{- A simple gameLoop of hangman.-}
module Hangman where
import qualified Data.Set as Set
import qualified System.IO as IO
import qualified System.Random as Rand
impor... |
Is there a better way of doing this? I heard that BinaryReader and Exif parsing to get the property item is faster, but I have no idea how to do that, thanks for the help.
//we init this once so that if the function is repeatedly called
//it isn't stressing the garbage man
static Regex r = new Regex(":");
//retrieves ... |
I'm stepping back into Android after being away from it for about a year. Trying to get an out of date app of mine back on its feet, and continuing work on it.
The app was written using Java, MVP, Realm, RxJava, and Dagger. I am trying to update it to use Kotlin, MVVM, Realm, Coroutines and ideally dropping Dagger, as ... |
I made a Java quiz program. The program will let you take the Java quiz and then display the quiz's result according to your score.
/*
* Java Quiz
* by Clint
* 2020.07.07
* This Java program let's you take a quiz. Quiz are taken at: https://www.w3schools.com/java/java_quiz.asp
*/
import javax.swing.JOptionPane;
... |
I am working on 957. Prison Cells After N Days
but getting timeout error for my code. as I assume my code should be 14+O(n-14) about O(n) am I right since after 14 run pattern will be repeated? and how can I improve my code?
from collections import defaultdict
step_map = defaultdict(list)
for k... |
The ubiquitous dplyr package has the function mutate_at (and many other *_at()'s), which allows us to perform a similar operation on multiple columns. Using purrr-style formulas, the relevant column is indicated by .:
df %>% mutate_at(vars(colA, colB, colC), ~ 2 * .)
This would double the values in the respective colu... |
I have been learning MVVM and I have decided to create a small framework for simple MVVM programs I can make in the future. This program provides navigation between a main menu, settings menu, start menu, and exit button. There is no functionality yet, and this is because I want to work on the navigation framework befo... |
The source code of this project aims to enable defining contact information either via FrontMatter or named parameters, and having that information then formatted to HTML that is both human and machine readable. I've attempted to adhere to the MicroCode specifications for both HCard and VCard formats, and allow for eas... |
I am trying to create a list based on some data, but the code I am using is very slow when I run it on large data. So I suspect I am not using all of the Python power for this task. Is there a more efficient and faster way of doing this in Python?
Here an explanantion of the code:
You can think of this problem as a li... |
In react I have a HTML Element Factory, it allows several different types of form elements to be created most with the same onChange but some have specific uses. I have been capturing them in this switch, but its time to refactor, what should an onChange() switch be converted to, should this too be a factory? Or just a... |
I created a syntax highlighter in JavaScript. The language it highlights is AdBlock Filter Syntax, the language used to write filters for ad blocker extensions in browsers.
Shown here is the AdBlockSyntaxLine Class, which is the core class that dices a line of text into categories. These categories are used to do highl... |
Looking for feedback on this code to reverse a double linked list. Things I am potentially looking for but missed -> redundant operations, extra / unnecessary arithmetic, improvement in code style. Thank yoU!
typedef struct Node {
int data;
struct Node* next;
struct Node* prev;
} Node;
void reverse(Node*... |
A few days ago I posted my password generator project to help me learn and become more comfortable. I got a lot of great replies from that and I've sense updated and would love another look at the program.
I've made it so that I can import it and use it to generator a password. I've also added support for completely cu... |
I'm using Temporal Tables on postgresql (https://github.com/arkhipov/temporal_tables) and C# with dapper.
I'm storing an entity together with its changes.
Here's an example entity, with an Id and two values. It was created in 2006 and underwent two simultaneous changes in 2007
| ID | IntValue | StrValue | sys_period ... |
I came across this question in a coding competition (Java-restricted) and I got a time-length-exceeded. I am unable to provide a link as the contest is closed now. Can I know how can I optimise this?
Unique Subsequences: You are given a randomly generated string of characters ranging from a to z. You are required to ... |
I have been working on this code to meet the best OOP standards for production. The code is working but I wish to make this a more efficient code. Could someone help me out here to make this efficient using best practices of ruby.
class Item
@@items = {}
def initialize(name, price)
@@items[name] = price
end
... |
I came across this question in a coding contest (Java-restricted) and I got TLE. I am unable to provide the link of the question as the contest is closed now. Can I know how can I optimise this?
Four Functions
Given four functions
A(x) = Number of i where 1 <= i <= x and gcd(i,x) = 1
B(x) = Sum of A(d) where d divide... |
Hello fellow programmers. I started learning C last week and today I wanted to see if I can make a working program, so I made this game:
/*
* TESTED IN LINUX - 2020
*/
#include <stdio.h>
#include <stdlib.h>
int player = 1, choice;
int places[10] = {'o', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
void switchPlaye... |
folks.
I have recently started writing software using Modern C++ 11-14. I have been developing software for more than a decade and just wanted to broaden my skillset. I am practicing building some simple design components using Modern C++. I dont have any friend or a colleague who knows c++ and noone can review my prac... |
I am building the list of items (TEST) with loadMore button with filter and want to have loading state in LoadMore button and items itself.
After loading the item I will fetch the detail of the first item for the first time and after that load the detail of the test.
This code does not contain the fetching of the deta... |
Back from a long C++ hiatus. I thought to implement mergesort from memory, using containers and not based on CLRS's pseudocode and arrays. The compiles and runs ok on the test cases.
/* TODOs
* Optimizations:
* [1] Have Mergesort sort values in-place: leftVec and rightVec contains references
*
* Improvements:
* ... |
We have a new service where an admin can upload a spreadsheet of new users they want to add to our application. During our processing we make a union map of all the users both existing and new additions, and check to make sure that the users will still be in a valid tree structure(s) after the update goes through.
Requ... |
I've made a Discord Bot in Python that uses the Psycopg module to make calls to a PostgreSQL database in order to display information.
https://github.com/Chombler/cardbot
Specifically, I call this function when a user calls the bot:
def pullCardRecord(recordName):
success = True
try:
print("Trying")
... |
What I wanted to do
As part of a larger project, I needed a simple text editor with line numbers. The editor should also be able to highlight the current line (line number in bold) and define the tab size.
The result looks like this:
My solution
After searching the internet for a while, I found out about the possibi... |
I wrote a bash script to move certain files within a group of directories with filenames that match certain conditions to another group of directories, but it is very cluttered. If possible, I want some help and tips regarding optimizing it:
#!/bin/bash
#Asks for user confirmation
echo "This will move all files in the... |
ERROR: type should be string, got "https://github.com/CascadeIllusion/DesmOEIS\nRecently began work on a Python project called DesmOEIS to build up my portfolio. It's a simple console program that looks up integer sequences from the OEIS, parses them, and converts them into Desmos lists using the Desmos API.\nThe program works fine, I just want general feedback to make sure I'm doing things the right way (not just code-wise, but also in terms of project structuring). Unit tests succeeded on my end, but then again maybe I'm not building good unit tests.\nconsole.py\nimport sys\nimport webbrowser\nfrom parsing import *\nfrom desmos import *\nfrom sequence import Sequence\n\n\ndef main():\n\n intro = \\\n \"DesmOEIS\\n\" \\\n \"A tool for converting OEIS sequences to Desmos lists.\\n\" \\\n \"\\n\" \\\n \"Type id=<OEIS id> (without the brackets) to convert a sequence. \\n\" \\\n \"Type help for a list of all valid commands. \\n\" \\\n \"Type exit to close the application. \\n\" \\\n\n help = \\\n \"\\nSyntax: (Command Name)=(Argument)\\n\\n\" \\\n \"id: Attempts to convert an OEIS id argument into a Desmos list. \\n\" \\\n \"The \\\"A\\\" is optional, and trailing zeros may be excluded.\\n\\n\" \\\n \\\n \"name: Assigns the resulting Desmos list to a variable with the given name. \\n\" \\\n \"Names must be exactly one letter character (except \\\"e\\\"), no numbers or special characters.\\n\\n\" \\\n \\\n \"trim: Filters a list using Python-style slicing syntax. For A:B:C:\\n\" \\\n \"A is the starting index (inclusive), default 0.\\n\" \\\n \"B is the ending index (exclusive), default is the list length.\\n\" \\\n \"C is a step value that is used to skip every C elements, default is 1 (don't skip anything).\\n\\n\" \\\n \\\n \"ext: Pass Y to this to output the extended version of the OEIS sequence.\\n\" \\\n \"WARNING: Passing an entire extended sequence this way is usually not a good idea, as such\\n\" \\\n \"sequences can be hundreds of elements long, and can cause your browser to hang. You may want\\n\" \\\n \"to combine this with trimming syntax to reduce the number of elements.\\n\\n\" \\\n \\\n \"view: Opens the .html file containing the last converted sequence since starting the program. \\n\" \\\n \"Does not work if used before converting a sequence.\\n\\n\" \\\n \\\n \"help: View a list of all valid commands.\\n\\n\" \\\n \\\n \"exit: Closes the application.\" \\\n\n print(intro)\n\n file = None\n\n while True:\n cmd = input()\n\n if cmd == \"help\":\n print(help)\n continue\n\n if cmd == \"view\":\n if file is None:\n print(\"No sequence converted yet.\")\n continue\n webbrowser.open(f\"file://{os.path.realpath(file)}\")\n continue\n\n if cmd == \"exit\":\n sys.exit()\n\n # Multiple commands are comma separated\n cmds = cmd.split(', ')\n cmds[-1] = cmds[-1].replace(',', '')\n\n if not cmds[0].startswith(\"id\"):\n print(\"First argument must be id.\")\n continue\n\n args = dict()\n\n for i in cmds:\n i = i.split(\"=\")\n\n cmd = i[0]\n value = i[1]\n\n args[cmd] = value\n\n id = parse_id(args)\n\n results = find_id(id)\n\n if results:\n sequence = Sequence(id)\n sequence.args = args\n sequence.results = results\n else:\n print(\"Invalid id.\")\n continue\n\n sequence.integers = parse_integers(sequence)\n\n name = sequence.args.get(\"name\")\n\n if name:\n if len(name) > 1:\n print(\"Variable names must be one character only.\")\n continue\n\n if str.isdecimal(name) or name == 'e':\n print(\"Numeric names and the constant e (2.71828...) are not allowed.\")\n continue\n\n sequence.name = name\n\n file = create_expression(sequence, create_desmos_list)\n\n print(\"Sequence converted successfully! \\n\")\n\n\nif __name__ == '__main__':\n main()\n\nparsing.py\nimport requests\n\n\ndef parse_id(args):\n\n id = args.get(\"id\")\n\n # Remove the preceding A if included\n id = id.replace('A', '')\n\n # Add trailing zeros if necessary\n length = len(id)\n if length < 6:\n for i in range(0, 6 - length):\n id = \"0\" + id\n\n # Add A at the beginning of the query\n id = 'A' + id\n\n return id\n\n\ndef find_id(id):\n\n url = f\"https://oeis.org/search?q=id:{id}&fmt=text\"\n r = requests.get(url)\n\n if \"No results.\" in r.text:\n return None\n\n return r\n\n\ndef parse_integers(sequence):\n\n text = sequence.results.text\n\n text = str.splitlines(text)\n\n rows = []\n\n if sequence.args.get(\"ext\") == \"Y\":\n\n b_id = sequence.id.replace('A', 'b')\n url = f\"https://oeis.org/{sequence.id}/{b_id}.txt\"\n r = requests.get(url)\n sequence.results = r\n text = r.text\n text = str.splitlines(text)\n\n for line in text:\n space = line.find(\" \")\n row = line[space + 1:]\n row = row.split(', ')\n rows.append(row)\n\n else:\n\n for line in text:\n if line.startswith('%S') or line.startswith('%T') or line.startswith('%U'):\n # integers start 11 characters into the line\n row = line[11:]\n row = row.split(',')\n rows.append(row)\n\n rows = [row for integer in rows for row in integer]\n\n # Remove empty elements resulting from commas at the end of the %S and %T rows\n rows = list(filter(None, rows))\n\n trim = sequence.args.get(\"trim\")\n\n if trim:\n if \":\" not in trim:\n print(\"Trim argument missing colons ( : ).\")\n return\n trim = trim.split(\":\")\n if not (trim[0] is \"\" or trim[1] is \"\"):\n for i in trim:\n if i.isdigit() and trim[0] >= trim[1]:\n print(\"Start value must be less than the end value.\")\n return\n if trim[0] is \"\":\n trim[0] = '0'\n if trim[1] is \"\":\n trim[1] = len(rows)\n for i in trim:\n i = str(i)\n if not i.isdigit():\n print(\"Invalid input for trim argument.\")\n return\n trim = list(map(int, trim))\n start = trim[0]\n end = trim[1]\n if len(trim) == 3:\n if trim[2] is 0:\n print(\"Step value cannot be zero.\")\n return\n step = trim[2]\n rows = rows[start:end:step]\n else:\n rows = rows[start:end]\n\n return rows\n\ndesmos.py\nimport os\nfrom sequence import Sequence\n\ndef create_expression(sequence, func):\n\n graph = open(\"../resources/desmos_graph_base.html\")\n graph = graph.read()\n\n expr = func(sequence)\n\n # Add another placeholder comment below the expression to allow for further expressions\n graph = graph.replace(\"<!-- PLACEHOLDER -->\", f\"{expr} \\n <!-- PLACEHOLDER -->\")\n\n sequence.graph = graph\n\n dir = \"../graphs/\"\n if not os.path.exists(dir):\n os.makedirs(dir)\n filename = f\"{dir}{sequence.id}.html\"\n out_graph = open(filename, \"w\")\n out_graph.write(graph)\n\n return filename\n\n\ndef create_desmos_list(sequence):\n\n integers = sequence.integers\n\n desmos_list = str(integers)\n desmos_list = desmos_list.replace(\"'\", \"\")\n\n name = sequence.name\n\n if sequence.args.get(\"name\") is not None:\n name = name + \"=\"\n else:\n name = \"\"\n\n expr = f\"calculator.setExpression({{ id: 'graph1', latex:\\\"{name}{desmos_list}\\\" }});\"\n return expr\n\nsequence.py\nclass Sequence():\n\n def __init__(self, id):\n self._id = id\n\n @property\n def id(self):\n return self._id\n\n @property\n def args(self):\n return self._args\n\n @args.setter\n def args(self, args):\n self._args = args\n\n @property\n def integers(self):\n return self._integers\n\n @integers.setter\n def integers(self, integers):\n self._integers = integers\n\n @property\n def results(self):\n return self._results\n\n @results.setter\n def results(self, results):\n self._results = results\n\n @property\n def name(self):\n return self._name\n\n @name.setter\n def name(self, name):\n self._name = name\n\ntest_parsing.py\nimport unittest\nfrom parsing import *\nfrom sequence import *\n\n\"\"\"\n# Example sequences used:\nhttp://oeis.org/A000045\nhttp://oeis.org/A000047\nhttp://oeis.org/A139827\n\"\"\"\n\n\nclass TestIdParsing(unittest.TestCase):\n\n def test_parse_id(self):\n args = {\"id\": \"A000045\"}\n self.assertEqual(\"A000045\", parse_id(args))\n\n def test_parse_id_no_prefix(self):\n args = {\"id\": \"000045\"}\n self.assertEqual(\"A000045\", parse_id(args))\n\n def test_parse_id_no_trailing_zeros(self):\n args = {\"id\": \"A45\"}\n self.assertEqual(\"A000045\", parse_id(args))\n\n def test_parse_id_no_trailing_zeros_no_prefix(self):\n args = {\"id\": \"45\"}\n self.assertEqual(\"A000045\", parse_id(args))\n\n def test_parse_id_six_digit(self):\n args = {\"id\": \"A139827\"}\n self.assertEqual(\"A139827\", parse_id(args))\n\n def test_parse_id_six_digit_no_prefix(self):\n args = {\"id\": \"139827\"}\n self.assertEqual(\"A139827\", parse_id(args))\n\n\nclass TestIdFinding(unittest.TestCase):\n\n def test_find_id_success(self):\n id = \"A000045\"\n self.assertNotEqual(None, find_id(id))\n\n def test_find_id_fail(self):\n id = \"A123ABC\"\n self.assertEqual(None, find_id(id))\n\n\nclass TestIntegerParsing(unittest.TestCase):\n\n def test_parse_integers(self):\n\n args = {\"\": \"\"}\n\n id = \"A000045\"\n\n integers = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946,\n 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578,\n 5702887, 9227465, 14930352, 24157817, 39088169, 63245986, 102334155]\n\n integers = list(map(str, integers))\n\n url = f\"https://oeis.org/search?q=id:{id}&fmt=text\"\n r = requests.get(url)\n\n sequence = Sequence(id)\n sequence.integers = integers\n sequence.results = r\n sequence.args = args\n\n self.assertEqual(integers, parse_integers(sequence))\n\n # Use a different sequence because most extended sequences are too big to reasonably fit\n def test_parse_integers_ext(self):\n\n args = {\"ext\": \"Y\"}\n\n id = \"A000047\"\n\n integers = [1, 2, 3, 5, 8, 15, 26, 48, 87, 161, 299, 563, 1066, 2030, 3885, 7464, 14384, 27779, 53782, 104359,\n 202838, 394860, 769777, 1502603, 2936519, 5744932, 11249805, 22048769, 43248623, 84894767,\n 166758141, 327770275, 644627310, 1268491353, 2497412741, 4919300031, 9694236886, 19112159929]\n integers = list(map(str, integers))\n\n url = f\"https://oeis.org/search?q=id:{id}&fmt=text\"\n r = requests.get(url)\n\n sequence = Sequence(id)\n sequence.integers = integers\n sequence.results = r\n sequence.args = args\n\n self.assertEqual(integers, parse_integers(sequence))\n\n\nif __name__ == '__main__':\n unittest.main()\n\n" |
I made a simple console basketball game using Java.
/*
* Java Basketball
* by Clint
* 2020.07.08 | 3:59AM
* This Java program let's the player play basketball in console.
*/
import java.util.Random;
import java.util.Scanner;
public class Basketball {
static String[] shoot = {"1 POINT!", "2 POINTS!", "3 POI... |
My main problems are making draw case and any player can choose a place which is chosen by another player here is the code :
#include <iostream>
using namespace std;
char board[3][3] = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}};
static int turnnumber = 1 ;
bool winner = false, flag = false ;
bool win(){
... |
I've spent some time on this as an answer elsewhere, and did my best to optimize it. But looking at the hill of indents seems like this can be improved. I've tried to implement an any() statement to replace the for break part, without any luck. Does anyone have any suggestions?
Groups = [[['NM1', 'OP', '1', 'SMITH', 'J... |
I need to log in users to web app in Javascript and PHP. So I have Javascript interface which send me accessToken to PHP which stores users data to DB and log user in. But the result code does not look like OOP but like a peace of garbage. May be I dont know how to write that code, so the question is if this peace of P... |
I am new to programming and have been taking the time to learn C# by reading, doing some classes online for Unity, and using Youtube. I think you learn more from doing your own projects so I decided to write a program that asked the user to enter a movie they have not seen and then store the movie titles into a list an... |
I'm beginning (for the third time in 5 years) to learn Haskell and decided to do a "More or less" console game (game pick a random number, you then have to guess which).
First the code, then my question :
import System.Random
import Text.Read(readMaybe)
main :: IO ()
main = do
gen <- getStdGen
let maxSecret = 1... |
I searched on the internet for an algorithm for permutations in C and I found the following function:
void permute(char *a, int l, int r)
{
int i;
if (l == r)
printf("%s\n", a);
else
{
for (i = l; i <= r; i++)
{
swap((a + l), (a + i));
permute(a, l + 1, r)... |
Any advice on how to make this code; cleaner, more effective, just overall better!
Program creates a 'post' in the console. The post has a:
message
create on date
score for 'upvotes' and 'downvotes'
Users are able to upvote or downvote the post using upvote or downvote with a simple trim and to lower applied to the s... |
Initially, this is not an attempt at early optimization, though it's thoroughly possible I'm looking in the wrong place :).
The following function returns a height value for aliased columns in a kind of voxel-style height-map renderer.
It is called many, many times for both AI and player controlled entities and used fo... |
Given an integer , compute the minimum number of operations(+1, x2, x3) needed
to obtain the number starting from the number 1.
I did this using this code:
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
int n;
cin >> n;
vector<int> v(n+1, 0);
v[1] = 1;
f... |
So i have a server which I send a Request to and it sends me back a list of rooms,Now i made a window for joining rooms and I'm trying to refresh it every 3 seconds but when i use the Timer thread to refresh the list it doesn't work if I use the normal refresh method with the Timer it works just fine.
Here's some code:... |
Is this a performant strategy to implement a stack in Kotlin to compare and delete values?
Expect
Create a stack in order to compare an array of asteroids (ASTs) and handle collisions (deletions), returning the final array of ASTs after collisions.
Each AST moves at the same speed
Negative numbers move left, positive ... |
Since i develop in Java, i got into the habit of not putting hardcoded text in my code.
For paths to files and folders I use the code below. I did it in a way that it was easy to set up and quick to understand, but i want to know if there are any solution more clean to do the same work ? A lib just for this ?
So if you... |
Hey I always used to create some pretty messy endpoints and I decided that it's about time to start writing cleaner code, I'll provide an example of how would I design an endpoint and I'll be thankful for any insights why is it good or bad practice to do it like this also I'd be more than happy if you provide your own... |
The easiest way to explain this problem is to show these two test cases:
assert solution('ABC') == ['A', 'B', 'C', 'AB', 'AC', 'BC', 'ABC']
assert solution('ABCD') == ['A', 'B', 'C', 'D', 'AB', 'AC', 'AD', 'BC', 'BD', 'CD', 'ABC', 'ABD', 'ACD', 'BCD', 'ABCD']
my solution is below:
def subsolution(lst, length):
re... |
My attempt at creating a snake game, in pygame. I tried to make it as simple as possible, but i feel it could be better in terms of best practice, and efficiency, along the idea of avoiding redundant code.
It would be appreciated, if anyone can give me advice in that regard.
import pygame
import time
import random
pyga... |
I have a text data file in SPWLA format; I cannot find a specification for it. It contains physical measurements and/or rock descriptions from wellbore core samples. It's fairly gross. The example here is substantially simplified:
text = """\
30 1
2001.10 0.00 2.11
40 1 2
-1002.0000 34.5678
30... |
this post is sort of a continuation of my answer on the following question: Fast Algorithm to Factorize All Numbers Up to a Given Number. As this post explains - We need to factorize all the numbers up to a large N.
At first I gave a python solution which was pretty slow (since - you know, python), than I decided to wr... |
I have an array with 40000 numbers that are floats or ints. I need to perform some calculation.
To do this I have used nested for loop, but the code is really slow. Can I use something instead of nested the for loop? Is there any other way to reduce the execution time?
When I changed to a list comprehension the executi... |
I have a system with 2 different processes. Process 1 starts process 2 and sets up an AnonymousPipe between the 2. Process 1 needs to run some code and needs to interact with process 2 to get info and commit changes. Process 2 runs on Python with references to C# code (since I'm more familiar with C#) so process 2 has ... |
The "game of 24" as I called it in the title is a maths game in which you are given four numbers and have to combine them in an expression using only the four basic arithmetic operations +, -, × and ÷ (and possibly using parenthesis) to achieve the final result of 24. You must use each digit exactly once.
For example, ... |
I'm coming from languages like Java and Python and I'm completely new to C++. Therefore, my knowledge is somewhat limited.
My goal is to implement a listener in C++ myself and I came up with a solution using function pointers and lambdas.
The design is different from other questions that I have seen on this site so I h... |
I have a pandas dataframe (called base_mortality) with 1 column and n rows, which is of the following form:
age | death_prob
---------------------------
60 | 0.005925
61 | 0.006656
62 | 0.007474
63 | 0.008387
64 | 0.009405
65 | 0.010539
66 | 0.01... |
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... |
I am slowly creating a flow field pathfinding solution for Unity3D. I'm trying to follow Elijah Emerson's description, which appears in the book 'Game AI Pro' (volume 1). In this question I ask about the Coordinates object which I use here. I have subsequently cached some variables.
In my tests, the stop watch has re... |
Cross-Posted from Stack Overflow
I am new to using condition_variables and unique_locks in C++. I am working on creating an event loop that polls two custom event-queues and a "boolean" (see integer acting as boolean), which can be acted upon by multiple sources.
I have a demo (below) that appears to work, which I woul... |
This is my very first interaction with databases. The goal is to setup a safe playground on an Arch box to create tables and make queries. I want to learn the basics without risking sudo rm -rf /.
#!/usr/bin/env bash
# This script initializes a new MariaDB database,
# without root privileges,
# and connects to it.
#... |
I'm posting my code for a LeetCode problem copied here. If you would like to review, please do so. Thank you for your time!
Problem
In a network of nodes, each node i is directly connected to another
node j if and only if graph[i][j] = 1.
Some nodes initial are initially infected by malware. Whenever two
nodes are di... |
Any advice on how to make this code; cleaner, more effective, just overall better!
Program setup object that is coming from the database. it loop the object adding to the viewmodel object. Then the object has a certain properties base on type. The config type will only have the setting and value objects.
class Program
... |
I followed the SLAP principle in the below code.
But with "Mixing Level Of Abstraction" (refer below code) I can avoid the single line methods.
My question is - is it good to avoid the single line method in this case? But I believe the code with "SLAP Principle" has better readability than the other one. Please share y... |
I'm posting my code for a LeetCode problem. If you'd like to review, please do so. Thank you for your time!
Problem
Write a program to solve a Sudoku puzzle by filling the empty cells.
A sudoku solution must satisfy all of the following rules:
Each of the digits 1-9 must occur exactly once in each row.
Each of the di... |
I have a json file - WorkflowNames.json with contents as -
["ImportOrder", "ValidateOrder", "ProcessOrder", "ArchiveOrder"]
My C# code to read this json file is -
private Dictionary<string, bool> GetWorkflowNames()
{
var appDataFolder = ConfigurationMgr.GetAppPath("App_Data");
var jsonFilePath = Path.Combine(appDa... |
Hello i'm coding a social site and I need to know how clean this code is. I read other answers people told me from my previous questions like this and used it as guidelines. So now I wanna know if anything could be improved. Thank you.
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
error_reporting(-... |
I am a beginner in Python and I have attempted to create a small script/program which allows the user to do the following:
Generate a single random password
Generate a number of passwords specified by the user of a certain length specified by the user to a text file in a location of their choice
Test the strength of... |
I am learning to use parameters and arguments in Java to make my coding efficient. I am open to suggestion if I've done something wrong with this code of mine.
import java.util.Scanner;
public class paramsAndArgs {
static String name, feeling;
public static void main(String[] args) {
doesSomething(na... |
Since memmem() isn't cross-platform, I'm trying to rewrite it from scratch. How does this look?
#define MemContainsStr(Str, StrLen, Substr) MemContainsMem(Str, StrLen, SubStr, sizeof(SubStr))
void *MemContainsMem(const void *StrStart, register unsigned long StrLen, const char *Substr, register const unsigned char Subst... |
I am working with an API of coupons from sites like Groupon. There are 2 fields in the JSON response (url and imgUrl) that return a url which directs them to the actual coupon and a picture of the business, respectively. Problem is that they contain sensitive information (my API KEY).
Below is my service (using spring ... |
I'm fairly new to Java and I'd like to know if there's any way to improve or refactor the prompt on validating integer values for best practices.
import java.util.Scanner;
public class Triangle {
public static void main(String[] args) {
int a, b, c;
Scanner in = new Scanner(System.in);
// Prompt for a
Syst... |
I have rewritten my little chat application and tried to pay attention to former hints and tips. The viewer and the writer have to run as seperate applications. the Writer.class basically stores messages as property files. The directory, where the files get stored, is watched by the Viewer.class and gets scanned every ... |
Good morning,
I've made the loop for the range, which is copied from one sheet to another. However I have no solution for trimming my code down, which looks like this:
Sub sunrise()
Dim i As Single
With Worksheets("7")
.UsedRange.Clear
.Range("a1").Value = "Latitude"
.Range("b1").Value = "-18"
.Range("c1").Val... |
Hello I've started learning javascript and today made my first calculator
I would like to hear any suggestions how could I did it better and good coding practices.
// Inputs fields used in program
let elements = document.getElementsByClassName("buttons");
let screen = document.getElementById('output');
let history = ... |
I have a pandas dataframe, df1:
id level val
1 l1 0.2
1 l2 0.1
and another dataframe which contains type for l1 level, df2:
id type
1 A
Similarly, df3 which contains type for l2 level as well as new ids:
id new_id type
1 19 A
1 19 B
1 20 A
1 20 B
Now I want type for l1 ... |
I implemented Quicksort in JavaScript. I'm trying to follow the best principles in JavaScript. In Ruby when you declare classes your able to use private for the methods that are private. I don't think there is anything like that in JavaScript.
class QuickSort {
sort(a) {
a = this.shuffle(a); //Shuffling is neede... |
I have this JSON code that I got from a get request with Azure API. Everything works how I want it but it doesn't look good. There must be an easier way to parse the data.
import json
#GET REQUEST code here, it works now the code below is grabbing the result and loading it.
formatted_response = {'cost': 0, 'timespan': ... |
My abstract class. Product will have multiple child classes those will be different types of Product
public abstract class Product
{
private int productId;
public int ProductId
{
get
{
return pro... |
I've started working on a text-based adventure game that has procedurally-generated levels. I am unfamiliar with the more popular methods so I just decided to generate the dungeon using a recursive method. However, my code looks quite amateur-ish with all the if statements and I am unsure of whether or not it could run... |
For a personal project (reading media file metadata) I created a small/fast utility class for working with RIFF chunks.
Support:
defining chunks by 32 bit integral value
defining chunks using 4 ASCII characters
splitting chunks into 2 16 bit integral values (useful for parsing RIFF headers)
comparing chunks for equali... |
win_xept.hpp - a basic windows api exception
#include "../utl_macro.hpp"
namespace xept
{
using win_t = struct utl_exception // utl_exception randomly generates a name
// this hides exception names from rtti
{
DWORD e = GetLastError( );
};
}
ramfile.hpp - an ... |
I was trying to solve one programming challenge :
First input is a list of connections which is made of pair of IPv4
address. Each IP has its own state which starts with false, each
connection also has state which is made up by logical AND of state of
its IPs
Second input is a toggle IPs list , these toggles the stat... |
I wrote a class for some MongoDB operations. So far I'm self-taught and mostly I follow the style from already existing code at my workplace (a startup).
We don't have a code-review culture, so I'm pretty new to the process, but I'm open fortips for everything from code optimization, better logging, better documentatio... |
I have written a function to multiply two numpy arrays.
def ra(self):
"""Multiply Rotation with initial Values"""
rva = self.r_array() * self.va_array()
rva = np.sum(rva, axis=1) # Sum rows of Matrix
rva = np.array([[rva[0]], # Transpose Matrix
[rva[1]],
[rva[2]... |
I feel like there's something wrong with the way my code is styled but I can't quite place what's wrong with it. Perhaps the way I've represented the snake is a little convoluted?
const HEIGHT = 20;
const WIDTH = 20;
const snake = function() {
const snakeCoordinates = [[0, 0], [1, 0]];
const moveDirections = [... |
I wrote a simple FIFO based on pieces of code I found online.
It's intended for embedded systems with very restricted RAM.
It's supposed to be very simple and efficient.
The size is always power of 2 (8, 16, 32, 64, 128 etc).
fifo.h
#ifndef FIFO_H
#define FIFO_H
struct fifo
{
volatile uint8... |
using System;
using System.IO;
class Solution {
static void Main(String[] args) {
int t = Int32.Parse(Console.ReadLine());
for(int a = 0; a < t; a++){
int currentNumber = Int32.Parse(Console.ReadLine());
int allSum = 0;
for(int i = 3;i<currentNumber;i+=3)**Calculate sum of 3**
{... |
I'm making an API call in my parent component in React. I'm making a weather app, and theres two different endpoints I'm getting data from. I'm getting 5 day forecast, and the current weather data.
I have two separate functions for the API calls, and I then call them functions in the componentDidMount function. I'm usi... |
For my second week of learning C, I decided to remake the Tic Tac Toe game I made last week, but in a different style (as some of you recommended me). This is my final product on the whole Tic Tac Toe game idea, so I tried my best. I feel like it is a bit overkill, but I want to know your opinion.
Here is the code:
/*
... |
I inherited a Xamarin project and I'm trying to find my way. The first task I completed involved creating a new reusable view and adding it to an existing screen. This was iOS specific, so I went and created a new .xib file to add in the relevant storyboard. I had some trouble figuring out how to attach the outlets cor... |
I am trying to learn Haskell and figured I would kill two birds with one stone and also learn about data compression. My ultimate goal is to implement the DEFLATE compression algorithm in Haskell. To start I have implemented lz77.
import Data.List
import Data.Maybe
import System.IO
import ... |
Please take a review of my simple bit manipulator:
#ifndef BIT_STREAM_H
#define BIT_STREAM_H
#include <cstdint>
class BitStream {
public:
explicit BitStream(uint8_t* buffer, size_t buffer_size) : m_Buffer(buffer), m_BufferSize(buffer_size) {
}
virtual ~BitStream() = default;
public:
inline uint64_t... |
I am using the function below to change the environment. If it sees the wrong environment values, it clicks on it and it changes the environment.
In this function, I am just using if and else statement. Is this a good code practice? This does the job however it does not seem clean.
class SettingsPage extends Page {
ch... |
This is my /forums page
<div class="card-body">
<h5 class="card-title">2019/2020 Premier League Forum</h5>
<a href="/Leagues/EnglishDivision/PremierLeague" class="btn btn-primary">View</a>
</div>
For the above code you can see the href pointing to a directory to premierLeague.hbs.
This is how my file structure loo... |
Hello all I have a short question. Is this a good and secure way to connect to my DB ?
session_start();
$servername = "localhost";
$un = "username";
$password = "password";
$dbname = "project";
$timezone = date_default_timezone_set("America/New_York");
// Create connection
$con = mysqli_connect($servername, $un, $pa... |
Background
The platform I'm coding for is an esoteric scripting engine coded some time ago that only has limited capabilities. Because I cannot produce a version of the engine that can be run on its own (it needs to attach to a running instance of a game), I have translated the code into C# with limitations to mimic th... |
I'm trying to come up with a function to convert byte arrays to their integer representation, using both
endianness, and with a signed/unsigned option.
enum class ByteOrder {
LITTLE,
BIG
}
fun ByteArray.toInt(byteOrder: ByteOrder = LITTLE, signed: Boolean = true): Int {
if (isEmpty()) {
throw Unsup... |
I have the same array set up as a variable inside of each function - I want to make this easier to manage. The array contains multiple strings of values. I’ve attached code below that I've been working on.
I would like to save this array to PropertiesService making it persistent across all executions. I already tried m... |
I need to extract unique Product Group names along with its corresponding services from a table in a worksheet. The table is generated by a bot and is not filtered, I have sorted it by alphabetical order. The data is not fixed and can contain anywhere from 5 - 100 rows of data, depending on the month which the report f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.