instruction stringlengths 71 95.1k |
|---|
This is my first time trying solve a game using these techniques.
I've looked at pseudocode of alpha-beta pruning with transposition tables and rewritten it in c++.
I'm also using bitboards inspired by Connect4.java as explained in John's Connect Four Playground.
I'm not solving Connect4, but instead a 5 by 5 variation... |
Right now I'm making a Discord Bot written in Python. I'm using SQLAlchemy to deal with the database.
My structure is:
One database.py containing a DatabaseConnection class initializing the SQLAlchemy engine, and making a new session with the DB every time i use it
Many .py file(each file for different purposes) conta... |
I have put together a To-do Application with the Slim framework on the back-end (API) and a Vue 3 front-end. I added a demo on my YouTube channel.
In the main App.vue file I have:
<template>
<div id="app">
<Header
title="My todo list"
:unsolvedTodos = unsolvedTodos
/>
<List
:todos="todos... |
This is a Python (3) script that converts numbers among 5 data formats: binary, decimal, hexadecimal and octal, it supports 16 conversions, that is, it can convert each of the five data formats to and from the other four data formats.
This script is adapted from my previous PowerShell script that does similar things: P... |
I have a match arm in rust, I think it may be simplified, but after googling and read books, I haven't find the solution. Especially for the str_vec.pop(), it returns an option type, I have to write a meanless () to make it compileable.
pub fn simplify_path(path: &String) -> String {
let mut str_vec: Vec<&str> = Ve... |
Its an Basic Calculator I worked on, and now I wanna know if I can make something better like not so "much" Code or I made somthing to complicated? Have a nice day! Keep safe!
import java.util.Scanner;
public class learningCode {
public static void main(String[] args) {
Scanner scan = new Scanner(System.i... |
I have this small C++ program for computing the \$n\$th Tribonacci number at compile-time. My main concern is: is it possible to get rid of the statickeyword (I had to use it in order to silence my compiler (VS 2019))?
Code
#include <cstdint>
#include <iostream>
template<uint64_t N>
struct tribonacci {
constexpr s... |
I have seen many posts regarding a standard 52-card deck of playing cards. I recently was composing an answer to one such post when I realized my answer should be its own post since (A) the answer diverged greatly from the OP and (B) my classes addressed my own objectives and not the OP's.
I have no specific questions... |
Here is my code that I recently made (I am a beginner). I used BeautifulSoup and Requests to get the data of this website. Please read over my code and tell me how to improve it. Thanks.
import random
import time
from os import system
import keyring
from bs4 import BeautifulSoup
import requests
def getdata(url):
h... |
I'm still in the process of learning Java / spring and I think I'm getting better. Now at this point I'm able to build a rest api BUT I'm at a lost at how to ensure I've no concurrency issues . I've read quite a bit of documentation on having my classes stateless and I "think" I've achieved that.
Could I get a code rev... |
This class acts as an asynchronous event handler that will execute all attached tasks in an async/await context. Requires Nuget Immutables. Example usage:
class MyEventArgs : EventArgs {}
async Task SomeAsyncMethodAobject src, EventArgs args) {
Console.WriteLine("Task A...");
await Task.Delay(2000);
}
async Tas... |
I wrote a short bash script for a completion check of downloading images.
goal of this code (Added)
I have some downloading content directories. Each of them has a script for downloading images(tmp.sh), for example, the following one:
wget -nc ¥
http://www.example.com/001.jpg ¥
http://www.example.com/002.jpg ¥
..... |
So I've been trying to implement a Token class in C++. At first I wanted to use a simple enum class to store the Kind of the Token.
But then I came across a problem. Some Tokens (such as keywords, identifiers, numeric literals, etc.) would need to store an external value along with their Kind, while others wouldn't. I ... |
My very first computer program, a very simple income tax calculator. What can I do to get the same outcome with better efficiency?
# 2021 income tax calculator
print ('What\'s your yearly income after you deduct all expenses?')
myincome = int(input())
base = (myincome*.1)
e = (max(myincome-9950,0)*.02)
ex = (max(myinco... |
I created a class to handle maps in my RPG game, before it became a class this was a collection of functions I created, but I thought it could be used as a class. although this code is working but i am not sure what i made. changing the function set to OOP confuses me.
import os
import pygame
import helper_func as hf... |
I am working on an SMS marketing project based on Yii2 Framework (PHP 7.3 & MariaDb (innodb engine)) where we have to move the logs from different tables to the archive db, which is total a different DB server from the live one.
The log tables keep growing and we had to setup an automated job which runs 3 times a week ... |
This is a random word generator I wrote in Python 3 today, I don't know how many Python implemetations of this exist, but this is my first try and it is completely working.
It returns a random word like string that is pronounceable (most likely pronounceable), I used some English letter frequency statistics data to ens... |
I've been learning Rust for a few weeks in my free time, and as a first project I decided to make a simple terminal Game of Life program (without UI, that might come later). It just starts with a glider and loops indefinitely (Torus topology). I decided to keep it simple so I can learn from early mistakes before I star... |
Can some one help me on how to eliminate repetition to reduce duplication score on the below classes created in the code
class EnquiryFilterSerializer(serializers.ModelSerializer):
class Meta:
model = enquirylog
fields = '__all__'
class EnquirySerializer(serializers.ModelSerializer):
class Met... |
Hello Code Review community !
I'm making a bot with discord.py that listens to every message sent in a server and stores it in a database that could be retrieved by admin/mod later.
Here's the structure of the database currently
guild_id = guild.id
statements = [
f"""
CREATE TABLE guild{guild_id}_members (
... |
This module is the main GUI for a project I'm working on. It's not yet final, but I feel I've become somewhat blind to potential improvements / refactorings, but I'm sure there are plenty. The module started out as a mess, as I generated the code with QtDesigner. The code was neither readable nor maintainable (it's pro... |
How can I optimize and shorten this code that I am using to display Woocommerce custom fields?
function fields() {
global $product;
$value1 = get_post_meta( $product->id, 'storage', true );
$value2 = get_post_meta( $product->id, 'delivery_date', true );
$value3 = get_post_meta( $product->id, 'mpn', true );
$value4 = ... |
it's been two weeks since I started learning web development and am currently practicing designing a friend contact page. The problem is, I find my code very poorly optimized and can't do what I want. Do you have any suggestions on what changes I could make to my code?
For the HTML part, I feel like I put a little too ... |
I've been making a brute force program for fun. This program tries to guess a password using brute force. I've tried many things to help increase the efficiency. Here it is: (Sorry for the lack of comments)
from itertools import product
from time import time
def findamount(find):
constValues = ["a", "b", "c", "d", "e... |
Write a program that uses an ADT Stack to evaluate arithmetic expressions in RPN format. The contents of the stack should be displayed on the screen during evaluation. The allowed arithmetic operators are +, -, x, and /.
What I have done so far:
#include <iostream>
#include <string.h>
using namespace std;
struct S... |
I'm porting this code to Java and after a few tests all seems ok but I need to know if I'm doing this right.
The code takes some colors and create a color ramp for maps and other stuff. You can see the original Javascript version working here.
I removed the "slider" part and fixed the amplitude to 0..100 for color ramp... |
I have this function at the moment
def isConnected(adjacencyListMap: Map[String, Seq[String]]): Boolean = {
// Simple BFS to check whether each vertex is connected
val visitedMap = mutable
.Map[String, Boolean]() ++= adjacencyListMap.keys.map(vertex => vertex -> false).toMap
val seen = mutable.Stack... |
Below is the code for merge sort using multithreading. Will this code run for large number of inputs? Does any other part of the code need changing?
#include<iostream>
#include<thread>
#include<mutex>
#include<vector>
#include<functional>
#include<fstream>
std::mutex mut;
void merge(std::vector<int>& vec,int s,int m... |
Project Euler 7: What is the 10 001st prime number?
I currently have this code:
let primesfound = 0;
for(i=0;i<Number.MAX_SAFE_INTEGER;i++){
if(isPrime(i)){
primesfound++
}
if(primesfound==10001){
console.log(i)
break;
} else{
console.log(i + `and ${primesfound} found`) //testing line
}
}
but... |
from itertools import cycle
# Integers represent Chinese characters
main_text = "234458674935346547521456767378878473562561423"
text_with_commentary = "2344586749215432678652353465475214561655413164653413216576737887847356152352561423"
iter_main = iter(main_text)
iter_comm = iter(text_with_commentary)
marked_up = []... |
Take the words dataset from stringr. An R4DS exercise challenges the reader to check if there are any words in that dataset that contain every vowel. My presumably correct solution, using five calls to str_detect, was as follows:
library(stringr)
words[apply(sapply(c("a", "e", "i", "o", "u"), function(x) str_detect(wor... |
Background
I am doing an exercise in clojure to make a function that can determine if a number is an Armstrong Number or not.
The solution I came up with us a bit more complicated than it would be if there was not a requirement to take 17 digit numbers which start to cause calculation errors with Math/pow etc...
Tests
... |
I made a maze generator in python that outputs in CLI. With mazes that are extremely big, it can take a while to output. I want to know if there is any way to increase the efficiency of this code. Here it is:
import random
def mgen(size=3, disallowedcoords = [[]]):
try:
def canmove(coords, size, coordslist,... |
Goal
This code combines two matrices, diagonalizes that matrix, and finds the right and left eigenvectors, right and left eigenvectors are normalized with respect to each other, then it is multiplied by an exponential function that is a function of the Eigen values and plots the output spectrum with respect to omega(w:... |
The below code filters my contacts according to a search term the user typed.
Is there a way I can avoid explicitly writing all the object keys but keep the readability?
contacts = contacts.filter(
contact =>
contact.firstName.toLowerCase().includes(search) ||
contact.lastName.toLowerCase().includes(s... |
A function that asks for user input according to some criteria and again on the same line if the criteria is not met. It requires that escape character sequences be enable.
"""
Ask for user input according to some criteria
and again on the same line if the criteria is
not met
"""
__all__ = ['input_wrong_up_line']
de... |
The standard HTML range input element suffers from a number of limitations that caused me to implement the web component presented here.
First, it is unnecessarily complicated to style the standard HTML range input element to make it look the same in all web browsers (see here and here).
Second, the standard HTML range... |
I'm in the early stages of learning Racket, and decided to have a go at the tower of Hanoi. I did this without any reference whatsoever, so everything is up for review, including the algorithm as well as my code.
In order to move n disks from a from peg to a to peg, we need to...
move the top n-1 disks from from to fr... |
I have about 977 obs in top500Stocks which contains name of 977 stocks.
head(top500Stocks,10)
ï..Symbol
1 RELIANCE
2 TCS
3 HDFCBANK
4 INFY
5 HINDUNILVR
6 HDFC
7 ICICIBANK
8 KOTAKBANK
9 SBIN
10 BAJFINANCE
and I have Date, OHLC and Adj.Close, Vol and Ret of each stocks from th... |
I wrote this module to find the Hamming distance between two strings. (It's a problem from exercism.io's Haskell track.)
As I saw it, the problem has two distinct parts: check if the length of the two strings are equal (if not return Nothing), and recursive pattern matching on equal-length strings.
Since my score is a ... |
I decided I wanted to make a console-like system. So, I started planning & creating it in c#. Currently, all that it is is a processor of sorts. It reads all bytes from a file (R:\disk00), and then executes them, somewhat like a CPU. display.pyw is a simple pygame application which reads R:\disk01 and displays the char... |
I am currently participating in research on transient absorption spectroscopy and four wave mixing. In the experimental design, an extreme ultraviolet (XUV) laser pulse and infrared (IR) laser pulse are sent through a finite gas sample with a certain time delay between them. My current task was to develop a function th... |
I wrote a Pomodoro timer daemon for BSD systems in C (may work on Linux with -lbsd).
The server uses poll(2) and sockets to communicate with the client and to implement the timer.
The client starts or stops the timer and gets information about it.
For example, in a terminal run $ pomod (the server).
In another, run $ p... |
The below code segments compose a simple console game where the user is prompted to enter a randomly generated letter displayed in the console. It also saves and loads user data through a .txt file.
It's a good bit of code, so I'm looking for any sort of constructive criticism on the code. Feedback on how to achieve ... |
This is an old script I made a while ago.
What it does
It tracks your dose of whatever you want tracked (cigarettes, salt, etc), outputs the total for each day, and the full week.
What I’m looking for
I’ve recently been looking at map() and list comprehensions so I converted this script into both versions.
I’d like to ... |
So this is a programming challenge I saw:
Write a program that outputs all possibilities to put + or - or nothing between the numbers 1,2,…,9 (in this order) such that the result is 100. For example 1 + 2 + 3 - 4 + 5 + 6 + 78 + 9 = 100.
This is interesting, if useless.
Anyway I have written two scripts in Python 3 to... |
I have the following code where I am trying to map columns from the input file to output.
I have written it using multiple loops. Is there a way to write this more efficiently?
input.csv:
Name, Age, Gender, Nation
Joe, 18, Male, British
output.csv:
First_name, Age_Years, Gender_F_M, Religion, Nationality
Joe, 18, ... |
I am working on a Laravel application (Github repo) that requires user registration and login.
After registration, the users can change their registration details (except password, for which there is the default password recovery functionality) and add more info.
They also have the possibility to replace the default a... |
I have a lambda function which returns the nearest city from a latitude and longitude.
My algorithm for this is resource heavy and time consuming. To optimise this, I hash the coordinates into a 6 digit combination representing the 5km tile they are in. For example 'apHsvW' might refer to New York.
I save the hash in a... |
This is a follow-up question for Android APP FTP host profile class implementation and Android APP connect to FTP server in Java. I am attempting to perform the upload operation to specified FTP server in Android APP. With referring to the answer of FtpClient storeFile always return False and List of FTP server return ... |
This was written down solely as a mean to practice basic C++ and isn't meant to serve any production purposes. Clearly, the implementation can't handle all input formats: it always expects the CSV to have a header line, it doesn't treat quoted commas well, the file has to have a newline in the end, hardcoded separator,... |
I have a class called Thing. For simplicity, let's say it initializes with a unique id, and that's all that's unique about it:
class Thing {
id: string;
constructor(id: string) {
this.id = id;
}
}
Based on its id, a Thing will reference a specific item in the underlying database. It is essentially an abst... |
Some time ago, I participated in a Game Jam using Pygame for the first time and I faced a few difficulties with some of its elements, notably the sounds and the events. That's why I decided to create my own Pygame wrapper to simplify its use. I made it firstly for my personnal use, but as I uploaded it on GitHub, I wan... |
ERROR: type should be string, got "https://github.com/speedrun-program/load-extender\nThis is the previous version: lengthening the time it takes to access files REVISION #2\nTo compile this, you need to download and include robin_hood.h, and on Windows you also need to install EasyHook.\nI made this because it helps us save non-load time in a speedrun.\nIn this version, it uses unique_ptr int arrays instead of a class, it has a way to include leading and trailing spaces in file names, and it has a way to deal with if there’s already a file named files_and_delays.txt. I also made it so the txt files are in utf-16 LE on Windows because that’s how file paths are encoded on that OS.\nload_extender.cpp\n#include <chrono>\n#include <thread>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <mutex>\n#include <filesystem>\n#include <memory>\n#include <climits>\n\n#ifndef THIS_IS_NOT_THE_TEST_PROGRAM\n#define THIS_IS_NOT_THE_TEST_PROGRAM\n#endif\n\n#ifdef _WIN32\nusing wstring_or_string = std::wstring;\n#include <Windows.h>\n// easyhook.h installed with NuGet\n// https://easyhook.github.io/documentation.html\n#include <easyhook.h>\n#else\nusing wstring_or_string = std::string;\n#ifndef _GNU_SOURCE\n#define _GNU_SOURCE\n#endif\n#include <dlfcn.h>\n#endif\n\n#include \"robin_hood.h\"\n#include \"other_functions.h\"\n// thank you for making this hash map, martinus.\n// here's his github: https://github.com/martinus/robin-hood-hashing\n\nstatic robin_hood::unordered_node_map<wstring_or_string, std::unique_ptr<int[]>> rh_map;\nstatic std::mutex delay_array_mutex = read_delays_file(rh_map);\n\n#ifdef _WIN32\nstatic NTSTATUS WINAPI NtCreateFileHook(\n PHANDLE FileHandle,\n ACCESS_MASK DesiredAccess,\n POBJECT_ATTRIBUTES ObjectAttributes,\n PIO_STATUS_BLOCK IoStatusBlock,\n PLARGE_INTEGER AllocationSize,\n ULONG FileAttributes,\n ULONG ShareAccess,\n ULONG CreateDisposition,\n ULONG CreateOptions,\n PVOID EaBuffer,\n ULONG EaLength)\n{\n const std::wstring& file_path = ObjectAttributes->ObjectName->Buffer;\n // +1 so '\\' isn't included. If '\\' isn't found, the whole wstring is checked because npos + 1 is 0\n const std::wstring& file_name = file_path.substr(file_path.rfind(L\"\\\\\") + 1);\n delay_file(rh_map, file_name, delay_array_mutex);\n return NtCreateFile(\n FileHandle,\n DesiredAccess,\n ObjectAttributes,\n IoStatusBlock,\n AllocationSize,\n FileAttributes,\n ShareAccess,\n CreateDisposition,\n CreateOptions,\n EaBuffer,\n EaLength\n );\n}\n\nextern \"C\" void __declspec(dllexport) __stdcall NativeInjectionEntryPoint(REMOTE_ENTRY_INFO * inRemoteInfo);\n\nvoid __stdcall NativeInjectionEntryPoint(REMOTE_ENTRY_INFO* inRemoteInfo)\n{\n HOOK_TRACE_INFO hHook1 = {NULL};\n LhInstallHook(\n GetProcAddress(GetModuleHandle(TEXT(\"ntdll\")), \"NtCreateFile\"),\n NtCreateFileHook,\n NULL,\n &hHook1\n );\n ULONG ACLEntries[1] = {0};\n LhSetExclusiveACL(ACLEntries, 1, &hHook1);\n}\n#else\nstatic auto original_fopen = reinterpret_cast<FILE * (*)(const char* path, const char* mode)>(dlsym(RTLD_NEXT, \"fopen\"));\n\nFILE* fopen(const char* path, const char* mode)\n{\n // finding part of path which shows file name\n int file_name_index = -1; // increases to 0 and checks entire path if no slash is found\n for (int i = 0; path[i] != '\\0'; i++)\n {\n if (path[i] == '/')\n {\n file_name_index = i;\n }\n }\n const std::string file_name(&path[file_name_index + 1]);\n delay_file(rh_map, file_name, delay_array_mutex);\n return original_fopen(path, mode);\n}\n#endif\n\nload_extender_test.cpp\n#include <mutex>\n#include <memory>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <filesystem>\n#include <climits>\n#include \"robin_hood.h\"\n// thank you for making this hash map, martinus.\n// here's his github: https://github.com/martinus/robin-hood-hashing\n\n#ifdef _WIN32\nusing wstring_or_string = std::wstring; // file paths are UTF-16LE on Windows\n#else\nusing wstring_or_string = std::string;\n#endif\n\n#include \"other_functions.h\"\n\nstatic void print_rh_map(robin_hood::unordered_node_map<wstring_or_string, std::unique_ptr<int[]>>& rh_map)\n{\n printf(\"\\n---------- hash map current state ----------\\n\");\n for (auto& it : rh_map)\n {\n#ifdef _WIN32\n printf(\"%ls /\", it.first.c_str());\n#else\n printf(\"%s /\", it.first.c_str());\n#endif\n int i = 1; // used after loop to check if -1 is at the end\n for (; it.second[i] >= 0; i++)\n {\n printf(\" %d\", it.second[i]);\n }\n if (it.second[i] == -1)\n {\n if (i == 1)\n {\n printf(\" RESET ALL\");\n }\n else\n {\n printf(\" REPEAT\");\n }\n }\n printf(\": INDEX %d\\n\", it.second[0]);\n }\n printf(\"---------------------------------------------\\n\\n\");\n}\n\nstatic void test_all_inputs()\n{\n#ifdef _WIN32\n wchar_t path_separator = L'\\\\';\n#else\n char path_separator = '/';\n#endif\n wstring_or_string test_path;\n std::ifstream input_test_file;\n input_test_file.open(\"test_input.txt\", std::ios::binary);\n if (input_test_file.fail())\n {\n printf(\"couldn't open test_input.txt\\n\");\n return;\n }\n std::string file_content(\n (std::istreambuf_iterator<char>(input_test_file)),\n (std::istreambuf_iterator<char>())\n );\n if (file_content.length() > 0 && file_content[file_content.length() - 1] == '\\n')\n {\n file_content.erase(file_content.length() - 1);\n }\n input_test_file.close();\n#ifdef _WIN32\n if (file_content.length() < 2)\n {\n printf(\"test_input.txt byte order mark is missing\\nsave test_input.txt as UTF-16 LE\\n\");\n return;\n }\n size_t start_index = 2; // first two bytes are BOM bytes\n#else\n size_t start_index = 0;\n#endif\n size_t stop_index = 0;\n robin_hood::unordered_node_map<wstring_or_string, std::unique_ptr<int[]>> rh_map;\n std::mutex delay_array_mutex = read_delays_file(rh_map);\n print_rh_map(rh_map);\n do // go through each line\n {\n#ifdef _WIN32\n stop_index = file_content.find(\"\\n\\0\", start_index);\n if (stop_index != std::string::npos)\n {\n // - 1 because of carriage return character\n test_path = string_to_wstring(file_content.substr(start_index, stop_index - start_index - 1));\n }\n else\n {\n test_path = string_to_wstring(file_content.substr(start_index));\n }\n start_index = stop_index + 2; // + 2 to go past newline character and null character\n printf(\"testing path: %ls\\n\", test_path.c_str());\n#else\n stop_index = file_content.find(\"\\n\", start_index);\n if (stop_index != std::string::npos)\n {\n test_path = file_content.substr(start_index, stop_index - start_index);\n }\n else\n {\n test_path = file_content.substr(start_index);\n }\n start_index = stop_index + 1; // + 1 to go past newline character\n printf(\"testing path: %s\\n\", test_path.c_str());\n#endif\n // +1 so separator isn't included\n // If separator isn't found, the whole wstring is checked because npos + 1 is 0\n const wstring_or_string& test_file = &test_path[test_path.rfind(path_separator) + 1];\n delay_file(rh_map, test_file, delay_array_mutex);\n print_rh_map(rh_map);\n test_path.clear();\n }\n while (stop_index != std::string::npos);\n}\n\nint main(int argc, char* argv[])\n{\n printf(\"\\ntest start\\n\");\n test_all_inputs();\n printf(\"test finished, press Enter to exit\\n\");\n std::string x;\n std::getline(std::cin, x);\n return 0;\n}\n\nother_functions.h\n#ifndef THIS_IS_NOT_THE_TEST_PROGRAM\n#include <iostream>\n#endif\n\n#ifdef _WIN32\nstatic std::wstring string_to_wstring(std::string line)\n{\n std::wstring ws_line;\n for (size_t i = 1; i < line.length(); i += 2)\n {\n ws_line.push_back((line[i - 1]) + (line[i] << 8));\n }\n return ws_line;\n}\n#endif\n\nstatic void remove_start_and_end_whitespace(wstring_or_string& file_name)\n{\n wstring_or_string white_space = {9, 11, 12, 13, 32}; // whitespace character values\n size_t first_not_whitespace = file_name.find_first_not_of(white_space);\n size_t last_not_whitespace = file_name.find_last_not_of(white_space);\n if (first_not_whitespace == std::string::npos)\n {\n file_name.erase(0);\n }\n else\n {\n file_name = file_name.substr(first_not_whitespace, last_not_whitespace - first_not_whitespace + 1);\n }\n}\n\nstatic void set_key_and_value(robin_hood::unordered_node_map<wstring_or_string, std::unique_ptr<int[]>>& rh_map, wstring_or_string& line)\n{\n#ifndef THIS_IS_NOT_THE_TEST_PROGRAM\n static bool too_big_delay_seen = false; // this is used so the message will only be printed once\n#endif\n // 47 is forward slash, 45 is dash character, 10 is newline\n // numbers used so it will work with both string and wstring\n int current_delay = 0;\n size_t current_index = (line.length() > 0 && line[0] == 47); // start at 1 if first character is forward slash\n wstring_or_string file_name;\n std::vector<int> delay_sequence;\n delay_sequence.push_back(1); // first index keeps track of next index to get delay time from\n // get file name\n for (; current_index < line.length() && line[current_index] != 47 && line[current_index] != 10; current_index++)\n {\n file_name.push_back(line[current_index]);\n }\n if (line[0] != 47) // remove leading and trailing whitespace if first character wasn't forward slash\n {\n remove_start_and_end_whitespace(file_name);\n }\n // get delay sequence\n for (current_index++; current_index < line.length() && line[current_index] != 10; current_index++)\n {\n if (line[current_index] >= 48 && line[current_index] <= 57) // character is a number\n {\n int current_digit = line[current_index] - 48;\n // avoid going over INT_MAX\n if (((INT_MAX / 10) > current_delay) || ((INT_MAX / 10) == current_delay && (INT_MAX % 10) >= current_digit))\n {\n current_delay = ((current_delay * 10) + current_digit);\n }\n else\n {\n#ifndef THIS_IS_NOT_THE_TEST_PROGRAM\n if (!too_big_delay_seen)\n {\n too_big_delay_seen = true;\n printf(\"delay time can only be %d milliseconds\\n\", INT_MAX);\n }\n#endif\n current_delay = INT_MAX;\n }\n }\n else if (line[current_index] == 47)\n {\n delay_sequence.push_back(current_delay);\n current_delay = 0;\n }\n else if (line[current_index] == 45)\n {\n delay_sequence.push_back(-1); // sequence starts over after reaching the end\n current_delay = 0;\n break;\n }\n }\n if (current_delay != 0)\n {\n delay_sequence.push_back(current_delay);\n }\n if (delay_sequence[delay_sequence.size() - 1] != -1)\n {\n delay_sequence.push_back(-2); // sequence ends without starting over\n }\n if (delay_sequence[1] != -2) // no delay sequence written on this line\n {\n std::unique_ptr<int[]> delay_sequence_unique_ptr = std::make_unique<int[]>(delay_sequence.size());\n // copy delays into std::unique_ptr<int[]>\n for (size_t i = 0; i < delay_sequence.size() && i < INT_MAX; i++)\n {\n delay_sequence_unique_ptr[i] = delay_sequence[i];\n }\n // delay sequence can't be longer that INT_MAX because first index keeps track of next index to get delay time from\n if ((delay_sequence.size() > INT_MAX) || ((delay_sequence.size() == INT_MAX) && (delay_sequence[INT_MAX] >= 0)))\n {\n#ifndef THIS_IS_NOT_THE_TEST_PROGRAM\n printf(\"only %d delays can be stored in a delay sequence\\n\", INT_MAX - 2);\n#endif\n delay_sequence_unique_ptr[INT_MAX] = -2;\n }\n rh_map[wstring_or_string(file_name)] = std::move(delay_sequence_unique_ptr);\n }\n}\n\nstatic std::mutex read_delays_file(robin_hood::unordered_node_map<wstring_or_string, std::unique_ptr<int[]>>& rh_map)\n{\n std::ifstream delays_file;\n std::string txt_file_name = \"files_and_delays.txt\";\n // find files_and_delays.txt file with highest number at the end\n // this is used in case the directory already has a file named files_and_delays.txt\n for (int file_number = 0; std::filesystem::exists(\"files_and_delays\" + std::to_string(file_number) + \".txt\"); file_number++)\n {\n txt_file_name = \"files_and_delays\" + std::to_string(file_number) + \".txt\";\n }\n#ifndef THIS_IS_NOT_THE_TEST_PROGRAM\n printf(\"opening %s\\n\", txt_file_name.c_str());\n#endif\n delays_file.open(txt_file_name, std::ios::binary);\n if (delays_file.fail())\n {\n#ifndef THIS_IS_NOT_THE_TEST_PROGRAM\n printf(\"couldn't open %s\\n\", txt_file_name.c_str());\n#endif\n return std::mutex();\n }\n std::string file_content(\n (std::istreambuf_iterator<char>(delays_file)),\n (std::istreambuf_iterator<char>())\n );\n delays_file.close();\n#ifdef _WIN32\n if (file_content.length() < 2)\n {\n printf(\"files_and_delays.txt byte order mark is missing\\nsave files_and_delays.txt as UTF-16 LE\\n\");\n return std::mutex();\n }\n size_t start_index = 2; // first two bytes are BOM bytes\n#else\n size_t start_index = 0;\n#endif\n size_t stop_index = 0;\n do // go through each line\n {\n#ifdef _WIN32\n stop_index = file_content.find(\"\\n\\0\", start_index);\n std::wstring line = L\"\";\n if (stop_index != std::string::npos)\n {\n // - 1 because of carriage return character\n line = string_to_wstring(file_content.substr(start_index, stop_index - start_index - 1));\n }\n else\n {\n line = string_to_wstring(file_content.substr(start_index));\n }\n start_index = stop_index + 2;\n#else\n stop_index = file_content.find(\"\\n\", start_index);\n std::string line = \"\";\n if (stop_index != std::string::npos)\n {\n line = file_content.substr(start_index, stop_index - start_index);\n }\n else\n {\n line = file_content.substr(start_index);\n }\n start_index = stop_index + 1;\n#endif\n set_key_and_value(rh_map, line);\n }\n while (stop_index != std::string::npos);\n return std::mutex();\n}\n\nvoid delay_file(robin_hood::unordered_node_map<wstring_or_string, std::unique_ptr<int[]>>& rh_map, const wstring_or_string& file_name, std::mutex& delay_array_mutex)\n{\n#ifndef THIS_IS_NOT_THE_TEST_PROGRAM\n#ifdef _WIN32\n char print_format[] = \"%ls\";\n#else\n char print_format[] = \"%s\";\n#endif\n#endif\n robin_hood::unordered_node_map<wstring_or_string, std::unique_ptr<int[]>>::iterator rh_map_iter = rh_map.find(file_name);\n if (rh_map_iter != rh_map.end())\n {\n#ifndef THIS_IS_NOT_THE_TEST_PROGRAM\n printf(print_format, file_name.c_str());\n printf(\" found in hash map\\n\");\n#endif\n int delay = 0;\n {\n std::lock_guard<std::mutex> delay_array_mutex_lock(delay_array_mutex);\n std::unique_ptr<int[]>& delay_sequence = rh_map_iter->second;\n if (delay_sequence[1] == -1)\n {\n for (auto& it : rh_map)\n {\n it.second[0] = 1;\n }\n#ifndef THIS_IS_NOT_THE_TEST_PROGRAM\n printf(\"all delay sequences reset\\n\");\n#endif\n }\n else if (delay_sequence[delay_sequence[0]] == -1)\n {\n delay_sequence[0] = 1;\n#ifndef THIS_IS_NOT_THE_TEST_PROGRAM\n printf(print_format, file_name.c_str());\n printf(\" delay sequence reset\\n\");\n#endif\n }\n#ifndef THIS_IS_NOT_THE_TEST_PROGRAM\n else if (delay_sequence[delay_sequence[0]] == -2)\n {\n printf(print_format, file_name.c_str());\n printf(\" delay sequence already finished\\n\");\n }\n#endif\n delay = delay_sequence[delay_sequence[0]];\n delay_sequence[0] += (delay_sequence[delay_sequence[0]] >= 0); // if it's -1 or -2, it's at the end already\n#ifndef THIS_IS_NOT_THE_TEST_PROGRAM\n delay *= (delay >= 0); // it might be set to -1 or -2\n printf(print_format, file_name.c_str());\n printf(\" access delayed for %d second(s) and %d millisecond(s)\\n\", delay / 1000, delay % 1000);\n#endif\n }\n#ifdef THIS_IS_NOT_THE_TEST_PROGRAM\n if (delay > 0) // it might be set to -1 or -2\n {\n std::this_thread::sleep_for(std::chrono::milliseconds(delay));\n }\n#endif\n }\n#ifndef THIS_IS_NOT_THE_TEST_PROGRAM\n else\n {\n printf(print_format, file_name.c_str());\n printf(\" not found in hash map\\n\");\n }\n#endif\n}\n\nload_extender_injector.cpp (only used on Windows because LD_PRELOAD and DYLD_INSERT_LIBRARIES can be used on Linux and Mac OS)\n#include <tchar.h>\n#include <iostream>\n#include <string>\n#include <Windows.h>\n// easyhook.h installed with NuGet\n// https://easyhook.github.io/documentation.html\n#include <easyhook.h>\n\nvoid get_exit_input()\n{\n std::wcout << \"Press Enter to exit\";\n std::wstring input;\n std::getline(std::wcin, input);\n std::getline(std::wcin, input);\n}\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n WCHAR* dllToInject32 = NULL;\n WCHAR* dllToInject64 = NULL;\n LPCWSTR lpApplicationName = argv[0];\n DWORD lpBinaryType;\n if (GetBinaryType(lpApplicationName, &lpBinaryType) == 0 || (lpBinaryType != 0 && lpBinaryType != 6))\n {\n std::wcout << \"ERROR: This exe wasn't identified as 32-bit or as 64-bit\";\n get_exit_input();\n return 1;\n }\n else if (lpBinaryType == 0)\n {\n dllToInject32 = (WCHAR*)L\"load_extender_32.dll\";\n }\n else\n {\n dllToInject64 = (WCHAR*)L\"load_extender_64.dll\";\n }\n DWORD processId;\n std::wcout << \"Enter the target process Id: \";\n std::cin >> processId;\n wprintf(L\"Attempting to inject dll\\n\\n\");\n // Inject dllToInject into the target process Id, passing \n // freqOffset as the pass through data.\n NTSTATUS nt = RhInjectLibrary(\n processId, // The process to inject into\n 0, // ThreadId to wake up upon injection\n EASYHOOK_INJECT_DEFAULT,\n dllToInject32, // 32-bit\n dllToInject64, // 64-bit\n NULL, // data to send to injected DLL entry point\n 0 // size of data to send\n );\n if (nt != 0)\n {\n printf(\"RhInjectLibrary failed with error code = %d\\n\", nt);\n PWCHAR err = RtlGetLastErrorString();\n std::wcout << err << \"\\n\";\n get_exit_input();\n return 1;\n }\n else\n {\n std::wcout << L\"Library injected successfully.\\n\";\n }\n get_exit_input();\n return 0;\n}\n\n" |
I don't know if my test cases at the bottom cover every case, or if my mathematical logic in the reducer function is exactly right (referring to the math that starts with (d1 + d2 >= 10)). More importantly I'm uncomfortable with the readability of this code as it's rather compact and difficult to parse, so any feedback... |
taken from leetcode.com:
A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return the skyline formed by these buildings collectively.
[...]
please review this code. I'm most interested in f... |
I have made this Pagination Class in JS which takes the following configurations :-
Total records
Records per page
Visible pages
The idea is simple that any instance created using this Pagination class should be easy to use and separate the view logic from the pagination logic. I have also added few validations as pe... |
Basic Description
What is the program for?
This is just a hobby project for me to improve at coding, not a serious one.
What does the program do?
It can take a chess position (not including variations like chess960 etc.), and generate all legal moves from it. Draw and checkmates are not added yet.
File and function des... |
In a previous question, Java logger (of doom!), I had posted my own logger, written in Java. I have since taken the answers from that question and a few of my own things to update it.
New code:
/*
* Syml, a free and open source programming language.
* Copyright (C) 2021 William Nelson
* mailto: catboardbeta AT gmail... |
I need a program same as I wrote but using loops. (if else for etc.) . Program is that enter a number and get each digits of number like that: number is 123456. I'm beginner, I can't create the logic and can't combine loops. Can anybody help me about that situation?
1.digits is 6
2.digits is 5
3.digits is 4
4.digits i... |
I had this trivia game, and from the review I got I improved my game. One of the improvements I made was this short function, to check the correctness of an answer (so if the correct answer was "Yellowstone park in Wyoming", "Yellowstone park" could be accepted. The code I have below works, but I would like it to be sm... |
When I need a singleton class in my Ruby code (for example, single logger for multiple classes) I usually use code like this:
class Parent_Singleton
@singleton = nil
def self.new
@singleton || (@singleton = super)
end
end
This approach allows me to avoid using the module Singleton (because I don't want to ... |
I have a for loop where I either increment or decrement the value of i by 1 each iteration. If start is greater than end I have to decrement i and if end is greater than start I have to increment i
I had written the for loop like so below, in order to keep it always starting at i = start and ending at i = end
However, ... |
This program asks the user for a players name, # of goals, saves, games played, etc. This information is ten organized on a .txt file along with the time the information was logged. users can also compare the players based on # of goals, Assists and saves made.
If anything can be improved, cleaned or replaced let me kn... |
I got this question as a coding challenge and was unable to get it done under 50 milliseconds (my solution takes >100 ms) :D
Would you please review my code and share any idea how to do this within 50ms?
Problem Description
One of our customers, a multinational company that manufactures industrial appliances, has an in... |
I've written this class to wrap a collection of bytes and interpret them as 16-bit floats. It's supposed to work like memoryview(buf).cast('f') or array.array('f', buf) I'm trying to avoid converting back and forth between values as much as possible. cPython does not currently support using the format code 'e' as the f... |
I have implemented Binary_Search in python (I think), and my own method for range objects. I want to know if there is any way to improve this code, here it is:
def findAmountString(string, char):
amount = 0
for n in range(len(string)):
if string[n] == char: amount += 1
return amount
def findrange(rangeToFind)... |
This project I'm dealing with will read the size of free memory segments and size of processes from a text file and then will try to allocate a memory partition for each process using the first-fit, best-fit and worst-fit allocation algorithms. Below is the first part of the code I wrote.
import sys
filename = sys.arg... |
I have this code which I use to append data to a JSON file. It will be helpful if someone could suggest pointers on:
Reducing file opening and closing
Make the write_json function efficient
and other general pointers. Thanks a lot.
#include <stdio.h>
#include <string.h>
#define ENTRIES_PER_LOG 10000
static int packe... |
The following code was written with the intent to be as efficient as possible, where efficiency includes speed of execution, memory usage, and lines of code, all in support of the primary design constraint that it can change the payload argument buffer in-place (from the calling function's perspective).
In its current ... |
The program will read size of free memory partitions and size of processes from a text file and then will try to allocate a memory partition for each process using the first-fit algorithm.
Input example:
300,600,350,200,750,125
115,500,358,200,375
My code for the implementation:
import sys
filename = sys.argv[1]
w... |
This is for a cheap VPS I use for personal projects. I like having a message of the day displaying system info on login; I wanted to add the status of my docker containers to it, to see if all are running and whatnot.
The scripts I found online for this displayed all the containers, but since I run mailcow for my email... |
The code below is a Haskell implementation of Needleman-Wunsch algorithm for sequence alignment (and string edit distance). It's an experiment in trying to closely imitate the dynamic programming method as it would be implemented in imperative languages. Hence my use of mutable arrays and ST monad.
{-# LANGUAGE ScopedT... |
I'm 16 years old and no one to help me, no one to give any advice or constructive criticism, I'm aimless. I'll leave the link to my last code (github), a program that sends an email to everyone registered in the database. I would like some advice and project/content ideas for me to evolve. Evaluate my project sincerely... |
This script gathers domains listed from sources in this JSON file and compiles them into one text file. Text files that have a similar key under the whitelists directory will have any matching domains removed. Any tips and tricks are welcome!
build.sh
#!/usr/bin/env bash
set -eu
if ! test -d sources; then
jq -r '... |
I'm implementing a system, which requires an order to be active.
I have a class called Yritys, which is the customer account who would have credits.
1 credit would mean 1 day of service use.
Yritys (company) has properties for credit (amount of credit) and OrderStartDate (when the original order was placed, credits wer... |
Given a (long) string src, generate substrings (up to) len characters long on demand by iterating over src and shifting the reading frame by shift characters every time.
StreamSupport.stream works for me, but is there a better (more idiomatic) way to do this, for example, by using a method like Stream.iterate and provi... |
Design a program to calculate the salaries of a company's employees based on the following data:
Number of hours worked.
The work shift performed: Morning (m), Afternoon (t), Night (n).
The ordinary hourly rate for each of the workers ($ 37.0).
For the calculation of the gross salary, take into account that the after... |
I am a bit concerned about style (functions, variable names, spacings, etc.). I am also not sure about whether I should return error or panic.
What do you think?
//SortStructs sorts user-made structs, given that "a" is a pointer to slice of structs
//and key's type (which is name of a field by which struct would be sor... |
The first time I used strtok, it felt, well, weird. But after a while, I became quite used to it. In a way it was simple. Soon after reading a bunch of Stack Overflow comments and posts about this function, I came to realize that this isn't what I should use in the long run.
Personally, my biggest problem with strtok w... |
I was working on one telgram bot, and when finally i made everything i discovered that it is extremely slow.
def s takes 5-7 seconds to get result and send it to user, i tried to optimise it with methods from other sites, but it didn't work.
How can i optimise it?
import telebot
import pyscp
from googlesearch import se... |
code climate tells me this block of code has a Cognitive Complexity of 7 (exceeds 5 allowed). Any ideas how I would refactor this to reduce complexity?
const validateDays = (param, days, dateValues) => {
if (!days || !param) {
return;
} else if (param === 'from' && dateValues) {
const disabledDays = {
... |
Below is an implementation of a UTF-8 string to UTF-16 string. Kind of like MultiByteToWideChar on Win32, but it's cross-platform and constexpr. Passing null as the output simply calculates the size. It works in my testing.
#include <stddef.h>
namespace utf_converter {
namespace detail {
constexpr bool utf8_trail_byte... |
I'm reading Bruce Molay's book on Unix programming, and as an exercise I've implemented a copy of the tail command.
My approach goes over the entire file once, to count newlines, then again to store their positions in an array, and finally a third time to print out the bytes past the position of the nth newline. I know... |
I created an algorithm for generating Latin Square. The algorithm uses the first n permutations (Not n!) orderings of a distinct row of numbers. This is then assigned to a 2d list.
import itertools
def latin_square(rows, numbers):
assert rows is not None, "row is required to not be None"
assert rows >= 0, "row... |
roux is a Rust library that wraps the Reddit API. Neither Reddit nor roux provides a stream-like interface for obtaining the latest submissions automatically, so that's what I've implemented here.
I'm learning Rust as a hobby (I'm a Python developer by trade) and this is my first "serious" Rust project. Please feel fre... |
A junior developer here.
I wrote a simple javascript custom element code here: https://codepen.io/rndbox/pen/mdWxryw as clean as I could with some advice from Junior Vs Senior Code - How To Write Better Code.
If possible, I would appreciate, if any willing Javascript Senior developer could improve / re-write my code in... |
Sifting is used to create a Latin Square of distinct symbols. The sifting is implemented by swaps on an array. The symbols might be strings or integer, but they are required to be distinct. Notably, this requires deep copy so that the whole Latin Square is not sifted by the same 1.
import copy
def make_latin_square(... |
The code is written in TypeScript.
export function waitFor<T, R> (
reducer: (acc: R, value: T) => R,
initial: R,
condition: (accumulated: R) => boolean,
): OperatorFunction<T, R> {
return (source$: Observable<T>) => {
return new Observable<R>((subscriber) => {
let accumulated: R = initial
return... |
I recently picked up C, because I am getting tired of the hell that is Java Enterprise development.
I decided that writing a Huffman compressor will be a great little exercise, and I have always wanted to write a compression algorithm.
I want some pointers(get it) on how to make the code more idiomatic, modular and les... |
Can someone give me any suggestions over my code that I made for this task?
Also how much of 10 would rate it ?
Suppose a simply linked list whose node is of type node and
contains a student's name, registration number, and grade(vathmos), such as
shown below:
struct node
{
char name [30];
int ΑΜ;
float vathmos;
struct... |
I'm 16 years old and no one to help me, no one to give any advice or constructive criticism, I'm aimless. I'll leave the link to my last code (github), a program that sends an email to everyone registered in the database. I would like some advice and project/content ideas for me to evolve. Evaluate my project sincerely... |
I've created a server file, that keeps waiting for clients. When someone connects to the server, he can send messages to the server, and from the server it is broadcasted to all clients.
Can you criticize my simple chat? Any possible improvements and changes are welcome. I have 2 files:
Server:
import threading
import... |
While reading Simply Scheme by Brian Harvey and Matthew Wright:
Part I: Chapter 2 Functions
In this chapter you are going to use the computer to explore functions, but you are not going to use the standard Scheme notation as in the rest of the book. That’s
because, in this chapter, we want to separate the idea of fu... |
for some reason the function setlocale(LC_ALL, "English") doesn't work when using an input function,(getchar, scanf, fgets,..), to get a special character, (Ç, ã, õ, é,...).
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
int cont = 0;
int soma = 0;
char resposta;
int main (vo... |
I wrote the following Python library for getting a callable's argument names, testing whether a callable takes an argument with a given name, and filtering a dict down to just the keys that a callable accepts. You can see the entire code (tests etc.) on GitHub; only the actual module itself is shown below.
Aside from ... |
Happily picked up Haskell a couple days back and working on the following use case.
Given a list of JSON objects with date fields and a start date, I want to create a list of weeks (here a tuple of dates, but improvements are welcome) from the start date to today plus a week, and count the number of days from the JSON ... |
Note: this script requires gmpy2, if you are using Python 3.9.5 x64 on Windows 10 21H1 like me, then you need to download the pre-built gmpy2 wheel from here: https://www.lfd.uci.edu/~gohlke/pythonlibs/.
So this is a script that approaches pi using 9 algorithms (actually only 7, two of the algorithms are implemented in... |
Could anyone help me with below logic implementation. I am new to Javascript and have been practicing advanced functions. The below code does the job but is there a better way to achieve the same? I want to make my code perfect.
I am grouping by location and then getting the sentiments count.
// Feedback
const sentimen... |
I mainly write code for data analysis so don't think about or use OOP at all on the day job. I thought I'd have a go at a simple Monty Hall simulation in an object-oriented style to figure out how it works - specifically I based it on this: https://www.reddit.com/r/dailyprogrammer/comments/n94io8/20210510_challenge_389... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.