instruction stringlengths 71 95.1k |
|---|
I'm wondering how the following looks for a javascript Array-sum function:
function sum(...rest) {
let n = 0;
for (let elem of rest) {
n += elem;
}
return n;
}
console.log(sum(1,2,3));
console.log(sum(2));
Is this considered overly verbose code? For example, of these examples are much more... |
I have just put this code together, it's not quite the most elegant but it seems to get the job done. Does it seem alright? I could not find anywhere a "de Bruijn sequence algorithm", so I just made this up. I saw debruijnsequence.org, but I don't get what's going on in all its detail, didn't find an enumeration algori... |
I have built a sample Parser class on top of the csv module for basic checks that we normally need as the first step of pre-processing. I would love a bit of feedback on the code and any areas that I can improve upon in the code to make it more efficient.
import csv
from exceptions import CompulsoryHeaderCheckFailed
... |
Recently, I got a code test from NAB. Please take a look at this one and give me your idea.
Find the max value of an array of N integers.
E.g. [ 1, -6, 2, 0, 1011, -355]
Require: the max value is a multiple of 3 and the code focuses on the correctness, not performance.
def solution(A):
try:
if not isinsta... |
https://leetcode.com/problems/fibonacci-number/
The Fibonacci numbers, commonly denoted F(n) form a sequence, called
the Fibonacci sequence, such that each number is the sum of the two
preceding ones, starting from 0 and 1. That is,
F(0) = 0, F(1) = 1 F(n) = F(n - 1) + F(n - 2), for n > 1. Given n,
calculate F(n).
Exa... |
So the idea was to find out how many times each array component is considered by binary search when we search all possible needles for the haystack:
package com.github.coderodde.fun.binarysearch;
import java.util.Arrays;
public class BinarySearchSpotCounter {
public static int binarySearch(int[] haystack, int ne... |
I am trying to find if there is better way to do this recursion. I went through some examples of memoization but found myself struggling to implement that with my code.
example data: db_data and package_data
#input data
pack_data = {
"depends_on": [{"id": "NF_PART_TWO", "type": "prep"}],
"id": "NF_PART_ONE",
... |
I wanted to convert C++ data structures to JSON with little code. More specifically, I wanted to convert C++ data structures to nlohmann JSON representation.
Project context: The goal is to use this in a somewhat large professional application (~50k code-lines) deployed for years in a not so critical product. I'm just ... |
I've implemented AES encryption in C to get more familiar with the language and to understand how encryption works better. I understand this code is unsuitable for actual cryptographic use and I'd like feedback which focuses more on code style/quality than security related things.
aes.h
#include <stdint.h>
#include <st... |
Can you help me think of some way to reduce the computational time of a code that generates a certain value, which in this case I call coef, which will depend on id/date/category? Better explanations below.
I made two functions that generate the same result. As you can see in benchmark, the first function (return_value... |
The context is a library to represent numbers (in this case integers) by wheighted position by radix powers for every radix R, passed as template argument. These derived types are digits of radix R, R_alphabet = {0,1,2,...,R-1}. The base class is to have holded the dig_t object as base_dig_t plus the radiz in the conta... |
I have the following code to register the dependency injection for automapper:
// Register Automapper
services.AddAutoMapper(
typeof(ApiProfile),
typeof(DomainToViewModelProfile),
typeof(DomainToDomainProfile));
// register lazy load automapper
var m... |
I'm so unsure that I am deallocating memory right. I am probably unable to figure out is shared_ptr destroyed or not, it seems to be impossible according to if checks, so maybe I need some try catch. I would like to listen ideas and ways of improving this code. Thanks. However, I'm so unsure that it prints that vector ... |
I don't know how to actually describe what this script does concisely.
I am writing GUI programs using PyQt6, and I want the most beautiful palette for my programs, so I browsed Wikipedia for a bunch of RGB values, and used them in my stylesheets.
The colors looked great, but there's one problem, my monitor has High Dy... |
The code below is for checking whether the input string is palindrome or not
const { argv } = require("process");
(()=>{
var palindrom01 = palindrom01;
palindrom01();
function palindrom01(){
let inputNum = argv[2];
let totalLength = inputNum.length;
let half_length = parseInt... |
First time using code review. I am still a student so there will be a lot to be desired.
Basically as part of the homework we are told what methods to create (Method names are given with their parameters). We essentially are parsing a bunch of files or raw CSV data looking for either specific names at a rank, names at ... |
I have the following function:
def get_resize_dimensions(new_width: int, new_height: int, width: int, height: int) -> tuple[int, int]:
"""Return the new width and height of an image, resized to the new width and height but maintaining the aspect
ratio. It will shorten along the edge that leaves the other edge l... |
Ok compiler is a bit of a stretch...
I'm working on a package manager for VBA code, written primarily in python. One fiddly step of the pipeline involves "compiling" packages; this is the process of taking VBA source code (.bas, .cls etc) and stuffing it into addin files for different VBA host apps (Excel .xlam, Access... |
I have a file format that I need to read which contains blocks of CSV data interspersed by non-CSV (or at least, inconsistent CSV) lines. Other than the very first line of the file (which has comma-separated headers), each repeated "block" has one line containing some metadata - including the number of actual CSV line... |
I'm trying to make the following code meaningful as much as possible, using inheritance. The purpose is for learning. The App class is the most super class. And the Tabs class has inherited it. Can I make the following code more meaningful and break it for more better classes? Instead of creating notebook = self.notebo... |
I'm working on building a simple game in vanilla JS (tic-tac-toe). Some weeks ago I created a functional MVP and asked some questions about it (Vanilla JS Tic-Tac-Toe). The code worked, but it was a single monolithic mess and the UI was ugly, so I decided to improve it.
So, I refactored the code. I organized it into th... |
This is a library that implements the logic of Connect Four.
There's nothing related to graphics or user input here. This library is supposed to be integrated into any environment where one could run C++ (and play Connect Four). I want it to be easy and straightforward to use in virtually any platform, from Desktop to ... |
I'm looking for feedback/improvement on code that I wrote. It's a function that scans a file for zlib headers and returns the header, offset, and decompressed data. In main, below the function, I use that data to find the offset beginning after the final zlib compressed data which I need that offset. I'm looking to imp... |
The below code is getting TLE error i.e Time limit Exceeded Error. I am finding it difficult to solve it without using nested for loops.Can someone tell a faster logic or can improve this code.
#include <stdio.h>
int mean(int arr[],int n,int b){
int m,s=0;
for(int i=0;i<n;i++){
... |
Interface:
Console output:
{
"Action": [
"Across The Void",
"Alien Shooter 2 Conscription",
"Alien Shooter 2 Reloaded",
"Aquaria",
"Assassin's Creed 3",
"Assassin's Creed 3 Liberation",
"Child of Light",
"Dragon Age 2",
"Dragon Age Origins",
... |
The fizzbuzz challenge presents a lot of interesting questions for 'intermediate' programmers like myself. I have found that I don't actually know where to draw the line with, complex (hard to read but concise/efficient) code and simple (easy to read but not concise) code. Additionally, I actually do not know if my 'mo... |
I watched a YouTube show the other day in which a variant of a Galton board is used to make a random selection from a range of movies that will be reviewed in that show. In contrast to a standard Galton board in which the ball is usually dropped from the mid-point, which results in a normal distribution, the starting p... |
This is my PHP algorithm for the twoSum problem in leetCode:
function twoSum($nums, $target) {
foreach($nums as $key1 => $num1) {
foreach(array_slice($nums, $key1 + 1, null, true) as $key2 => $num2) {
if ($num1 + $num2 === $target) {
return [$key1, $key2];
}
}... |
I wasn't sure where to post this, but I'm just looking for a brutally honest critique of a program that I built. I'm new to coding and am taking my first course on it. I'm just trying to determine if my code is awful and I should consider a different career path, or if it looks like I'm heading in the right direction. ... |
just wanted someone to review my code and perhaps simplify it a bit. Everything is working as expected for the moment but it seems too much code for what i'm trying to achieve. Especially the function "toggleItems". It just feels ... not right.
GOAL: The idea is that i'm having a list with a fixed set of items. When se... |
I have written a program that parses this code but it doesn't use recursive descent. So I am starting over and need help.
Just so everyone is on the same page:
Using recursive descent it needs to parse an input file and generate the GUI that it defines, using a supplied lexical analyzer. The grammar for this is defined... |
Overall, I want to make a game in console, something Pokemon-like but with typical rpg scenery - swords, magic and all that. I want to make player able to move around the map, find dungeons, fight some monsters (in a round-like maner, like Pokemon but you fight yourself, four moves, being able to escape, potions, etc.)... |
Mostly just looking for a review of my regex and implementation of capture groups. its something I've been working to improve.
The indexes have somewhat of a pattern to them of being....
(<level - not at surface>, <parameter>, <(unit) - not on every parameter>)
indexs
indexs = ('Sfc Prs(mb)', 'Mean SLP (mb)', 'Altimete... |
I'm working on this C++ coding problem:
Input is a sequence of up to commands, one per line, ending at
end of file. Each command is a definition, a calculation, or a clear.
All tokens within a command are separated by single spaces.
A definition has the format def x y where x is a variable name and y
is a an integer ... |
I have built a scraper that scrapes data from e-commerce website and saves it to json using my own module. Although, I made the scraper multi-threaded, it starts slow, then speeds up and uses a lot of cpu, after collecting 3000 items (not all the products in the website) it quits. It is working, but I feel like I have ... |
Subset Product is an NP-complete problem and is my favorite problem. So, I've written a slightly smarter way of solving the problem.
Will performance impact matter if I use multi-cpus and my GPU?
Do my variable names make sense of what I'm doing?
Is there a better way to write the for-loop under the variable "max_com... |
I would like to know if this is the best/most efficient/industry standard way of converting from the http response to an array of typed values:
Type class:
export class University {
public "state-province": string;
public country: string;
public name: string;
constructor(state_province: string, country: string... |
I had just decided to learn JavaScript, so I wrote this program. I am sure you know what FizzBuzz is so I wouldn't describe it here.
Console output:
Welcome to Node.js v15.12.0.
Type ".help" for more information.
> const special = [[15, 'FizzBuzz'], [5, 'Buzz'], [3, 'Fizz']];
undefined
>
> function fizzbuzz (number) {
... |
I am creating a template function with variardic arguments, to handle a specific classes that have some interface, method, member or whatever is specialized in a specialization area. However I came to a solution to handle even types that are not supported, thus avoid exceptions, polymorphism, virtual functions, RTTI, e... |
For some quick context, I'm fairly new to Rust and decided to give myself a difficult-but-attainable task of implementing a sorting algorithm. I chose bogosort (or stupid-sort, shuffle-sort, whatever your preference is) and got it working pretty quickly.
I then decided to make it faster by threading it lol.
This works ... |
I have tried to implement a Stack and associated functions in C, in order to understand the data structure better. Just wanted to know what do you think about my code overall.
Furthermore, I am using 0 as a value to set "empty section of the stack", and I know this is ambiguous - any suggestion on how to improve that a... |
This is a simple JavaScript function that does prime factorization.
I wrote it on an Android phone with online editor (I don't have access to computers in night time):
Code:
function factorize(n) {
if (!(Number.isInteger(n) && n >= 2)) {
throw 'Input is invalid'
}
const factors = []
while (n % 2 == 0) {
... |
Have posted here a while ago, I've read the answer and now I tried to apply the observations. This is the new code, I hope is it better than before. One thing I'm not sure if I used it properly is when I used EXIT_FAILURE and how.
Also, the 'early-return' point from the original answer, I did not do it. To I were to ap... |
I'm learning python and i'm trying to practice what I learned recently.
I wanted to make a quiz game using pandas.
What do you guys think? Is there anything I could do better?
import random
import pandas as pd
pd.options.mode.chained_assignment = None # default='warn'
"""We need one excel file(kerdesek.xlsx), then we... |
Code from: https://stackoverflow.com/a/65715088/6859121
It is use a mixed Json path to set Json value. Even if the object on the path does not exist.
This code seems to have room for improvement.
Is there some way, logical or flow to do the same thing that I don't know?
//Origin code by Squirrel.Downy(Flithor)
using N... |
Right here, I'm trying to identify whether or not the demand order in my multi-level BOM list is made by an anonymous customer and then update accordingly.
-In laymens term, I'm checking if an item in the "BOM list sheet" is an anonymous order. If it is, match the item to the same item in "other sheet" & check whethe... |
I have used an adjacency list to represent the graph.
This implementation is based on the procedure given in the book 'Introduction to Algorithms'.
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <stdbool.h>
typedef struct edge
{
size_t end_vertex;
int weight;
struct edge* next;
} E... |
I tried to initiate myself with unit testing the simplest way I can. What do you think of this way to begin with? Is it a clean way to proceed? Are there any major caveats to avoid?
NB:
Since I want to test a small script for each leetcode problem, I preferred to have the Test inside the script to be tested (and not i... |
I'm reading the famous Clean Code book of Robert C. Martin so I'm trying to refactor some of my latest code as exercise.
I feel like the method getTicket breaks the SRP (Single Responsibility Principle) as it does too many things (get the ticket, check if it's still valid, get a new one...).
On the other hand I don't s... |
I need code review. I've used Lombok and jackson. Static statemts look very "ugly" in Root class. I don't know what I should make with that. Is There another way to create nested classes?
Main class:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.gson.Gson;
import java.util.ArrayList;
imp... |
Intro
In order to get familiar with and improve my Rust skills I coded Tic-Tac-Toe. I want to write good Rust code, any feedback regarding why my code isn't in a Rust style or improvements that could be made would be very helpful.
Question
Is there a better way to implement my "new" method for the Ttt struct? I don't p... |
does anyone knows how I can simplify this code?
The objective is to get multiple files from the explorer and validate the number of files, the weight of each file and the total weight.
public static async Task<IEnumerable<StorageFile>> GetMultipleFileFromDisk(Window rootWindow, int maxFiles,
string fileType... |
Summary Append to list only if that value is the next value expected.
"""
Return codes can be wrong because errors happen. And the next return code can be reliant on this one.
This module checks that a return code is expected next and that only then does it become the latest piece of a
fulfilling order.
"""
__all__ ... |
Working code for my image detection script. This is functional code.
I'm loading a number of images into an array, and using two classes to generate the two main components I need for my detection; Vision and WindowCapture.
WindowCapture will grab a cropped section of your primary monitor to run detection on, while any... |
I have to extract all elements of array with the given list of coordinates and insert into 2*298808 as position given in while loop
How can I compress the code even more?
def arr_func(arr,selected_pixels_list):
rows = 2
m = 0
n = 0
i =0
#Calculate the number of pixels selec... |
Can I get some guidance around the usage of volatile keyword and design of the existing concurrent dictionary implementation, please.
Here are a few design considerations with my implementation:
Initially I thought I could have a simple dictionary and guard it by a single lock. It would work but I think the throughput... |
Generalizations of Fibonacci numbers
Fibonacci numbers of higher order
A Fibonacci sequence of order \$n\$ is an integer sequence in which each
sequence element is the sum of the previous \$n\$
elements (with the exception of the first \$n\$
elements in the sequence).
The usual Fibonacci numbers are a Fibonacci sequen... |
The following code builds a rudimentary acupuncture database by collecting data from the web.
I would like to hear suggestions about improvements to the database structure, code organization, web-scraping techniques etc.
(NOTE: Some tables created by the db script have not been fully populated. They are left here to in... |
This is a Python script that I wrote completely by myself. Basically it scans a giant picture to make a video.
They say one picture is worth more than a thousand words. Since a video contains thousands of pictures, a video is worth more than millions of words, so I will let the video outputs do the descriptions for me ... |
My recursive function works, but I feel it could be improved... suggestions? The code ensures that a given folder path exists by checking its validity or creating them if they don't already exist, so that afterwards I can, for example copy a file to the location.
Function EnsureFolderPath(strP As String) As Boolean
... |
On the basis of the daily exchange rate data of the CB (https://ww.cbr-xml-daily.ru/daily_json.js) it is necessary to create a Web-service using ASP.Net Core, which implements 2 API methods:
GET /currencies - should return the list of currencies with the possibility of pagination
GET /currency/ - must return the excha... |
I'm new to JS, so I'm most likely coding badly. Can you please point out the errors and correct the code? the site complains that it needs to write more text, but I don’t know what else to write
HTML
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" ... |
ERROR: type should be string, got "https://github.com/speedrun-program/load_extender\nThis is something I made and posted here about a year ago, but I decided to remake it.\nTo compile this on Windows, you need to install EasyHook.\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 <cstdio>\n// easyhook.h installed with NuGet\n// https://easyhook.github.io/documentation.html\n#include <easyhook.h>\n#include <Windows.h>\n\nvoid getExitInput(char ch)\n{\n for (; ch != '\\n'; ch = std::getchar());\n\n printf(\"Press Enter to exit\\n\");\n ch = std::getchar();\n}\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n WCHAR* dllToInject32 = nullptr;\n WCHAR* dllToInject64 = nullptr;\n _TCHAR* lpApplicationName = argv[0];\n DWORD lpBinaryType = 0;\n\n if (GetBinaryType(lpApplicationName, &lpBinaryType) == 0 || (lpBinaryType != 0 && lpBinaryType != 6))\n {\n std::printf(\"ERROR: This exe wasn't identified as 32-bit or as 64-bit\\n\");\n getExitInput('\\n');\n return 0;\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\n std::printf(\"Enter the process Id: \");\n long long int PIDLongLong = 0;\n char ch = std::getchar();\n\n for (; ch != '\\n'; ch = std::getchar())\n {\n if (ch >= '0' && ch <= '9')\n {\n ch = ch - '0'; // this prevents a warning message\n PIDLongLong *= 10;\n PIDLongLong += ch;\n }\n\n if (PIDLongLong > 4294967295)\n {\n std::printf(\"PID too large\\n\");\n getExitInput(ch);\n return 0;\n }\n }\n\n NTSTATUS nt = RhInjectLibrary(\n (DWORD)PIDLongLong, // 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 nullptr, // data to send to injected DLL entry point\n 0 // size of data to send\n );\n\n if (nt != 0)\n {\n std::printf(\"RhInjectLibrary failed with error code = %d\\n\", nt);\n PWCHAR err = RtlGetLastErrorString();\n std::printf(\"%ls\\n\", err);\n getExitInput(ch);\n return 0;\n }\n\n std::printf(\"Library injected successfully.\\n\");\n getExitInput(ch);\n return 0;\n}\n\nload_extender.cpp\n#include <cstdio>\n#include <climits>\n#include <mutex>\n#include <thread>\n#include <chrono>\n#include <vector>\n#include <string>\n#include <string_view>\n#include <unordered_map>\n\n#ifdef _WIN32\n// easyhook.h installed with NuGet\n// https://easyhook.github.io/documentation.html\n#include <easyhook.h>\n#include <Windows.h>\nusing wcharOrChar = wchar_t; // file paths are UTF-16LE on Windows\nusing strType = std::wstring;\nusing svType = std::wstring_view;\n#else\n#ifndef _GNU_SOURCE\n#define _GNU_SOURCE\n#endif\n#include <dlfcn.h>\nusing wcharOrChar = char;\nusing strType = std::string;\nusing svType = std::string_view;\n#endif\n\n// using multiple cpp files made exe bigger, so definitions are in this header\n#include \"shared_stuff.h\"\n\nstatic myMapType m;\nstatic std::mutex mutexForMap = setupMap(m);\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 wchar_t* path = (const wchar_t*)(ObjectAttributes->ObjectName->Buffer);\n int pathEndIndex = (ObjectAttributes->ObjectName->Length) / sizeof(wchar_t);\n int filenameIndex = pathEndIndex;\n\n for (; filenameIndex >= 0 && path[filenameIndex] != '\\\\'; filenameIndex--);\n\n filenameIndex++; // moving past '\\\\' character or to 0 if no '\\\\' was found\n auto it = m.find(svType(path + filenameIndex, (size_t)pathEndIndex - filenameIndex));\n\n if (it != m.end())\n {\n delayFile(m, it->second, mutexForMap);\n }\n\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 = { nullptr };\n HMODULE moduleHandle = GetModuleHandle(TEXT(\"ntdll\"));\n\n if (moduleHandle)\n {\n LhInstallHook(\n GetProcAddress(moduleHandle, \"NtCreateFile\"),\n NtCreateFileHook,\n nullptr,\n &hHook1\n );\n }\n\n ULONG ACLEntries[1] = { 0 };\n LhSetExclusiveACL(ACLEntries, 1, &hHook1);\n}\n#else\nstatic auto originalFopen = reinterpret_cast<FILE * (*)(const char* path, const char* mode)>(dlsym(RTLD_NEXT, \"fopen\"));\n\nFILE* fopen(const char* path, const char* mode)\n{\n int filenameIndex = -1;\n int pathEndIndex = 0;\n\n for (; path[pathEndIndex] != '\\0'; pathEndIndex++)\n {\n if (path[pathEndIndex] == '/')\n {\n filenameIndex = pathEndIndex;\n }\n }\n \n filenameIndex++; // moving past '/' character or to 0 if no '/' was found\n auto it = m.find(svType(path + filenameIndex, (size_t)pathEndIndex - filenameIndex));\n \n if (it != m.end())\n {\n delayFile(m, it->second, mutexForMap);\n }\n\n return original_fopen(path, mode);\n}\n#endif\n\nshared_stuff.h\n#ifndef DEBUG\n#define printf(...) (0)\n#endif\n\nclass FileHelper\n{\npublic:\n FileHelper(const FileHelper& fh) = delete;\n FileHelper& operator=(FileHelper other) = delete;\n FileHelper(FileHelper&&) = delete;\n FileHelper& operator=(FileHelper&&) = delete;\n\n FileHelper() {}\n\n ~FileHelper()\n {\n if (_f)\n {\n std::fclose(_f);\n }\n\n if (_fcheck)\n {\n std::fclose(_fcheck);\n }\n }\n\n void tryToOpenFile(const char* filename)\n {\n#ifdef _WIN32\n if (fopen_s(&_f, filename, \"rb\") != 0 || !_f)\n#else\n if (!(_f = std::fopen(filePath, \"rb\")))\n#endif\n {\n throw \"FileHelper fopen failure in tryToOpenFile\";\n }\n }\n\n bool checkIfFileExists(const char* filename)\n {\n#ifdef _WIN32\n bool exists = fopen_s(&_fcheck, filename, \"rb\") == 0;\n#else\n bool exists = (_fcheck = std::fopen(filePath, \"rb\"));\n#endif\n\n if (_fcheck)\n {\n std::fclose(_fcheck);\n _fcheck = nullptr;\n }\n\n return exists;\n }\n\n bool getCharacter(wcharOrChar& ch)\n {\n if (_bufferPosition == _charactersRead)\n {\n _bufferPosition = 0;\n _charactersRead = (int)std::fread(_buffer.data(), sizeof(wcharOrChar), _buffer.size(), _f);\n\n if (!_charactersRead)\n {\n return false;\n }\n }\n\n ch = _buffer.at(_bufferPosition);\n _bufferPosition++;\n\n return true;\n }\n\n void resetFile() // used in tests\n {\n if (std::fseek(_f, 0, SEEK_SET) != 0)\n {\n throw \"FileHelper fseek failure in resetFile\";\n }\n\n _bufferPosition = 0;\n _charactersRead = 0;\n }\n\nprivate:\n FILE* _f = nullptr;\n FILE* _fcheck = nullptr;\n std::vector<wcharOrChar> _buffer = std::vector<wcharOrChar>(8192 / sizeof(wcharOrChar));\n int _bufferPosition = 0;\n int _charactersRead = 0;\n};\n\nstruct MapValue\n{\n std::vector<int> delays;\n size_t position = 0;\n unsigned int fullResetCheckNumber = 0;\n bool reset = false;\n bool resetAll = false;\n};\n\nstruct KeyCmp\n{\n using is_transparent = void;\n\n bool operator()(const svType sv1, const svType sv2) const\n {\n return sv1 == sv2;\n }\n};\n\nstruct KeyHash\n{\n using is_transparent = void;\n\n size_t operator()(const svType sv) const\n {\n return _hashObject(sv);\n }\n\nprivate:\n std::hash<svType> _hashObject = std::hash<svType>();\n};\n\nusing myMapType = std::unordered_map<strType, MapValue, KeyHash, KeyCmp>;\n\nstatic bool makeMapValue(std::vector<int>& delaysVector, MapValue& mv, FileHelper& fh)\n{\n wcharOrChar ch = '\\0';\n bool textRemaining = false;\n long long int delay = 0;\n\n for (\n textRemaining = fh.getCharacter(ch);\n ch != '\\n' && textRemaining;\n textRemaining = fh.getCharacter(ch))\n {\n if (ch >= '0' && ch <= '9')\n {\n ch = ch - '0'; // this prevents a warning message\n delay *= 10;\n delay += ch;\n\n if (delay > INT_MAX)\n {\n throw \"delays can't be larger than INT_MAX\";\n }\n }\n else if (ch == '-')\n {\n if (delaysVector.empty())\n {\n mv.resetAll = true;\n }\n else\n {\n mv.reset = true;\n }\n\n break;\n }\n else if (ch == '/')\n {\n delaysVector.push_back((int)delay);\n delay = 0;\n }\n }\n\n if (delay != 0 && !mv.reset && !mv.resetAll)\n {\n delaysVector.push_back((int)delay);\n }\n\n // make sure to go to end of line\n for (; ch != '\\n' && textRemaining; textRemaining = fh.getCharacter(ch));\n\n return textRemaining;\n}\n\nstatic bool addMapPair(myMapType& m, strType& keyStr, std::vector<int>& delaysVector, FileHelper& fh)\n{\n keyStr.clear();\n delaysVector.clear();\n MapValue mv;\n wcharOrChar ch = '\\0';\n bool keepWhitespace = false;\n bool textRemaining = fh.getCharacter(ch);\n\n if (ch == '\\n' || !textRemaining)\n {\n return textRemaining;\n }\n else if (ch == '/')\n {\n keepWhitespace = true;\n }\n else if (ch != ' ' && ch != '\\f' && ch != '\\r' && ch != '\\t' && ch != '\\v')\n {\n keyStr.push_back(ch);\n }\n\n for (\n textRemaining = fh.getCharacter(ch);\n ch != '\\n' && ch != '/' && textRemaining;\n textRemaining = fh.getCharacter(ch))\n {\n if (keepWhitespace || (ch != ' ' && ch != '\\f' && ch != '\\r' && ch != '\\t' && ch != '\\v'))\n {\n keyStr.push_back(ch);\n }\n }\n\n if (textRemaining && ch == '/')\n {\n textRemaining = makeMapValue(delaysVector, mv, fh);\n }\n\n if (!keyStr.empty() && (!delaysVector.empty() || mv.resetAll))\n {\n mv.delays = delaysVector;\n strType keyStrCopy(keyStr);\n mv.delays.shrink_to_fit();\n keyStrCopy.shrink_to_fit();\n m.emplace(std::move(keyStrCopy), std::move(mv));\n }\n\n return textRemaining;\n}\n\nstatic std::mutex setupMap(myMapType& m)\n{\n try\n {\n std::wstring keyStr;\n std::vector<int> delaysVector;\n FileHelper fh;\n\n if (!fh.checkIfFileExists(\"files_and_delays0.txt\"))\n {\n fh.tryToOpenFile(\"files_and_delays.txt\");\n printf(\"opened files_and_delays.txt\\n\");\n }\n else\n {\n std::string name(\"files_and_delays1.txt\");\n unsigned int n = 1;\n\n while (fh.checkIfFileExists(name.c_str()))\n {\n n++;\n name = std::string(\"files_and_delays\" + std::to_string(n) + \".txt\");\n }\n\n name = std::string(\"files_and_delays\" + std::to_string(n - 1) + \".txt\");\n fh.tryToOpenFile(name.c_str());\n printf(\"opened %s\\n\", name.c_str());\n }\n\n#ifdef _WIN32\n wchar_t byteOrderMark = '\\0';\n\n if (!fh.getCharacter(byteOrderMark))\n {\n printf(\n \"files_and_delays.txt byte order mark is missing\\n\\\n make sure files_and_delays.txt is saved as UTF-16 LE\\n\"\n );\n }\n else if (byteOrderMark != 0xFEFF) // not 0xFFFE because of how wchar_t is read\n {\n printf(\n \"files_and_delays.txt byte order mark isn't marked as UTF-16 LE\\n\\\n make sure files_and_delays.txt is saved as UTF-16 LE\\n\"\n );\n }\n#endif\n\n while (addMapPair(m, keyStr, delaysVector, fh));\n }\n catch (char const* e)\n {\n char const* resolveC4101Warning = e;\n printf(\"%s\\n\", resolveC4101Warning);\n m.clear(); // clear map so failure is more obvious\n }\n\n return std::mutex();\n}\n\nstatic void delayFile(myMapType& m, MapValue& mv, std::mutex& mutexForMap)\n{\n#ifndef DEBUG // this needs to be reset in the test, so it's a global variable instead\n static unsigned int fullResetCount = 0;\n#endif\n\n printf(\"fullResetCount: %zu\\n\", fullResetCount);\n int delay = 0;\n\n {\n std::lock_guard<std::mutex> mutexForMapLock(mutexForMap);\n\n if (mv.fullResetCheckNumber < fullResetCount)\n {\n mv.position = 0;\n mv.fullResetCheckNumber = fullResetCount;\n printf(\"this delay sequence reset due to prior full reset\\n\");\n }\n\n if (mv.resetAll)\n {\n if (fullResetCount == UINT_MAX) // this probably won't ever happen\n {\n fullResetCount = 0;\n\n for (auto& it : m)\n {\n it.second.fullResetCheckNumber = 0;\n }\n\n printf(\"fullResetCount reset\\n\");\n }\n\n fullResetCount++;\n printf(\"fullResetCount set to %zu, all sequences will be reset\\n\", fullResetCount);\n }\n else if (mv.position == mv.delays.size())\n {\n if (mv.reset)\n {\n mv.position = 0;\n printf(\"this delay sequence reset\\n\");\n }\n else\n {\n printf(\"delay sequence already finished\\n\");\n }\n }\n\n if (mv.position < mv.delays.size())\n {\n delay = mv.delays.at(mv.position);\n mv.position++;\n }\n\n printf(\"delay is %d millisecond(s)\\n\\n\", delay);\n }\n\n if (delay > 0)\n {\n#ifndef DEBUG\n std::this_thread::sleep_for(std::chrono::milliseconds(delay));\n#endif\n }\n}\n\nload_extender_test.cpp\n#include <cstdio>\n#include <climits>\n#include <mutex>\n#include <vector>\n#include <string>\n#include <unordered_map>\n\n#ifdef _WIN32\nusing wcharOrChar = wchar_t; // file paths are UTF-16LE on Windows\nusing strType = std::wstring;\nusing svType = std::wstring_view;\n#else\nusing wcharOrChar = char;\nusing strType = std::string;\nusing svType = std::string_view;\n#endif\n\n#define DEBUG\nunsigned int fullResetCount = 0;\n\n// using multiple cpp files made exe bigger, so definitions are in this header\n#include \"shared_stuff.h\"\n\nvoid windowsHookFunction(myMapType& m, strType& pathStr, std::mutex& mutexForMap)\n{\n if (!pathStr.empty() && pathStr.back() == '\\r')\n {\n pathStr.pop_back();\n }\n\n const wcharOrChar* path = pathStr.c_str();\n\n int pathEndIndex = (int)pathStr.size();\n int filenameIndex = pathEndIndex;\n\n for (; filenameIndex >= 0 && path[filenameIndex] != '\\\\'; filenameIndex--);\n\n filenameIndex++; // moving past '\\\\' character or to 0 if no '\\\\' was found\n auto it = m.find(svType(path + filenameIndex, (size_t)pathEndIndex - filenameIndex));\n\n if (it != m.end())\n {\n#ifdef _WIN32\n printf(\"\\n%ls found in map\\n\", pathStr.c_str());\n#else\n printf(\"\\n%s found in map\\n\", pathStr.c_str());\n#endif\n delayFile(m, it->second, mutexForMap);\n }\n else\n {\n#ifdef _WIN32\n printf(\"\\n%ls not found in map\\n\", pathStr.c_str());\n#else\n printf(\"\\n%s not found in map\\n\", pathStr.c_str());\n#endif\n }\n}\n\nvoid unixHookFunction(myMapType& m, strType& pathStr, std::mutex& mutexForMap)\n{\n if (!pathStr.empty() && pathStr.back() == '\\r')\n {\n pathStr.pop_back();\n }\n\n const wcharOrChar* path = pathStr.c_str();\n\n int filenameIndex = -1;\n int pathEndIndex = 0;\n\n for (; path[pathEndIndex] != '\\0'; pathEndIndex++)\n {\n if (path[pathEndIndex] == '/')\n {\n filenameIndex = pathEndIndex;\n }\n }\n\n filenameIndex++; // moving past '/' character or to 0 if no '/' was found\n auto it = m.find(svType(path + filenameIndex, (size_t)pathEndIndex - filenameIndex));\n\n if (it != m.end())\n {\n#ifdef _WIN32\n printf(\"\\n%ls found in map\\n\", pathStr.c_str());\n#else\n printf(\"\\n%s found in map\\n\", pathStr.c_str());\n#endif\n delayFile(m, it->second, mutexForMap);\n }\n else\n {\n#ifdef _WIN32\n printf(\"\\n%ls not found in map\\n\", pathStr.c_str());\n#else\n printf(\"\\n%s not found in map\\n\", pathStr.c_str());\n#endif\n }\n}\n\nvoid printMap(const myMapType& m)\n{\n for (auto& it : m)\n {\n printf(\n#ifdef _WIN32\n \"%ls : fullResetCheckNumber %zu : position %zu : \",\n#else\n \"%s : fullResetCheckNumber %zu : position %zu : \",\n#endif\n it.first.c_str(),\n it.second.fullResetCheckNumber,\n it.second.position\n );\n\n for (size_t i = 0; i < it.second.delays.size(); i++)\n {\n printf(\"%d / \", it.second.delays.at(i));\n }\n\n if (it.second.reset)\n {\n printf(\"RESET\");\n }\n else if (it.second.resetAll)\n {\n printf(\"RESET ALL\");\n }\n\n printf(\"\\n\");\n }\n}\n\nvoid testFunctions(myMapType& m, FileHelper& fh, std::mutex& mutexForMap, bool testUnix)\n{\n strType pathStr;\n wcharOrChar ch = '\\0';\n\n while (fh.getCharacter(ch))\n {\n if (ch == '\\n')\n {\n if (testUnix)\n {\n unixHookFunction(m, pathStr, mutexForMap);\n }\n else\n {\n windowsHookFunction(m, pathStr, mutexForMap);\n }\n\n printMap(m);\n pathStr.clear();\n }\n else\n {\n pathStr.push_back(ch);\n }\n }\n\n if (testUnix)\n {\n unixHookFunction(m, pathStr, mutexForMap);\n }\n else\n {\n windowsHookFunction(m, pathStr, mutexForMap);\n }\n}\n\nvoid testInputs(myMapType& m, std::mutex& mutexForMap)\n{\n FileHelper fh;\n fh.tryToOpenFile(\"test_input.txt\");\n wcharOrChar byteOrderMark = '\\0';\n#ifdef _WIN32\n\n if (!fh.getCharacter(byteOrderMark))\n {\n printf(\n \"test_input.txt byte order mark is missing\\n\\\n save test_input.txt as UTF-16 LE\\n\\n\"\n );\n\n return;\n }\n else if (byteOrderMark != 0xFEFF) // not 0xFFFE because of how wchar_t is read\n {\n printf(\n \"test_input.txt byte order mark isn't marked as UTF-16 LE\\n\\\n make sure files_and_delays.txt is saved as UTF-16 LE\\n\\n\"\n );\n }\n#endif\n printf(\"\\ntesting UNIX\\n\\n - - - - - - - - - -\\n\\n\");\n printMap(m);\n testFunctions(m, fh, mutexForMap, true);\n printMap(m);\n fullResetCount = 0;\n fh.resetFile();\n#ifdef _WIN32\n fh.getCharacter(byteOrderMark);\n#endif\n\n for (auto& it : m)\n {\n it.second.position = 0;\n it.second.fullResetCheckNumber = 0;\n }\n\n printf(\"\\n\\ntesting Windows\\n\\n - - - - - - - - - -\\n\\n\");\n printMap(m);\n testFunctions(m, fh, mutexForMap, false);\n printMap(m);\n}\n\nint main()\n{\n try\n {\n printf(\"\\ntest start\\n\\n\");\n myMapType m;\n std::mutex mutexForMap = setupMap(m);\n testInputs(m, mutexForMap);\n }\n catch (char const* e)\n {\n printf(\"%s\", e);\n }\n\n printf(\"\\ntest finished, press Enter to exit\\n\");\n char ch = getchar();\n\n return 0;\n}\n\n" |
My code basically picks random letters and numbers from three lists and makes a random combination with them. I decided to write this code just for fun, however I feel like the code can be made shorter. I just don't know how.
So here is my code:
import random
caps=['A','B','C','D','E','F','G','H','I','J','K','L','M','... |
I need to implement a function/method that operates on a sequence of values, and acts kind of like takeWhile, but with 2 differences, first, it doesn't act on a single element, it is performed on a sequence of elements, second, it won't just return after the predicate is satisfied for the first time, it will keep goin... |
I have rather badly formatted questionnaires (i.e. ordered lists) in a bunch of documents that I want to clean up and replace the current version with the cleaned-up version.
Example text
STUDY: A trial of Passy-Muir valve was completed to allow the patient to achieve hands-free voicing and also to improve his secretio... |
My code basically organizes the files in a given directory based on the keyword inputted by the user, so for example if there is a directory with three files: sample 1.txt, sample 2.txt and random.txt and if the user inputted sample as the keyword then the program will make a folder named sample and move all files cont... |
I am learning JavaScript and decided to translate my Python scripts into JavaScript.
Approximations of π are extremely popular programming challenges and I am sure they must be a staple of the challenges one must overcome to learn a programming language.
I am sure you must be bored of this kind of questions but I have ... |
I tried to learn dynamic programming going from recursion to memoized version with the RodCutting problem: Returns the best obtainable price for a rod of length n and price[] as prices of different pieces.
Have you any suggestions on the code (or the way to make test), i tried to keep as simple and generic to mimic on... |
So I had this requirement to get the frequency of names appearing in a list
and then print the one appearing the most number of times. If there is a clash, print the one which comes first in the dictionary
so if I had
{"john", "johnny", "jackie", "johnny", "john", "jackie", "jamie", "jamie", "john", "johnny", "jamie", ... |
I am trying to write a program that does the following:
The application will read the customer and book orders data from a
data file “BookOrders.txt” and load them in a customer linked list,
each customer object contains an order linked list. The program will
allow user to place an order, update an order, cancel an or... |
The following code iterates over a table with nested th headings.
The decision has been made to just go with the main heading and ignore sub-headings, but nested structure still needs to be preserved to differentiate between the two.
The logic to traverse the rows and sub-rows correctly to preserve the nested structure... |
First post, very new to programming. This is my solution for the chapter 5 project of Automate the Boring Stuff and I wondered if I am making any mistakes and is there a way to make it more efficient using what the book has taught thus far.
The project description:
In this chapter, we used the dictionary value {'1h': ... |
I'm new to C++ and decided to write a parser for a markup language. I chose org-mode because it seemed relatively straightforward.
parsertest.cpp
#include <filesystem>
#include <fstream>
#include <iostream>
#include <regex>
#include <string>
#include <vector>
#include <nlohmann/json.hpp>
namespace fs = std::filesyst... |
I have this giant wall of code, which replaces the src of an img on the page with the one specified, for each link in a nav menu.
But... it's a giant wall of code, calling up the action for each individual ID tag. There's got to be a better way to do this, right? Am I missing something? Is there a way I can have a form... |
I am trying to compute a matrix-matrix product of N stacked complex double N x N matrices. For simplicity, I assume N = 512. I have written code in C++ parallelized with OMP and using OpenBLAS for the matrix-matrix product. This is the code:
#include <iostream>
#include <complex>
#include <chrono>
#include <openblas/cb... |
I am trying to store multiple lists to a database but I'm struggling on finding a better way of doing it, as the way I am doing it now, seems to be incorrect.
On my form, I have 6 different legs. Each leg consists of Cargo Weight, Bag Weight, Fuel Weight, and more.
Right now I am storing all the data to a new class cal... |
I made a snake game as console aplication. It was my first real little project I did all alone. I tried using best practices I learned but I've got lost few times so I suppose there will be some bad practices and bugs. I would like if someone has time to review my code and tell me what I did wrong so I can improve. I d... |
I made OOP sudoku generator - at this moment it generates only valid table. You can clear it and then generate over.
The case is I struggled with calling "fill_board" and "clear_board" form the button calss. So I made that class method, otherwise instance error appeard. It is finally working as intended but can you com... |
I wrote a very simple VM to get a bit more familiar with Rust. The VM architecture was not the focus, so that I think that can safely ignored. Is my code idiomatic and clean? I felt that I was very repetitive in some areas, namely the implementation of the binary operations.
Code:
use std::io::{self, Write};
#[derive(... |
DataFrame methods to parse the sky condition from a terminal aerodrome forecast.
A line in a taf can report zero-eight cloud layers. Cloud layers are required in predominate lines, and optional in temporary ones. Cloud cover SKC|FEW|SCT|BKN|OVC is associated to an octave value. 1, 3, 5, 8 as the min sky coverage for... |
I've rewritten my HTTP server several times over the past year, because I tend to encounter an issue midway through an implementation realizing I didn't abstract, decompose, or decouple certain methods properly. My primary goal with these rewrites is to slowly edge towards a modular and small, but still precise impleme... |
You will need to follow this guide.
This is a Youtube crawler that crawls information about Youtube playlists, it uses Youtube Data API v3 and it crawls the title, url, description, count and videos of the playlist.
For the videos it crawls the title, url, publish time, description, tags, category, duration, statistics... |
This button's code in gdscript 4 uses selector modes- only one possible at a time. It is attached to the 9 children small buttons of the main button.
There is singleton code that is just an array with each row being a string descriptor, a color, and three booleans- first sets whether to checked by Sudoku rules, second ... |
I have a device (ADC) that stores its samples in a 32-bit buffer and each sample is a 12-bit word :
I needed an algorithm to read those samples to a container (say std::vector<uint16_t>). So I started with the following reasoning (see the picture above):
The pattern consists of 3 32b-words
Any 12b-word is either enti... |
ERROR: type should be string, got "https://github.com/speedrun-program/load_extender\nThis is the previous post: Lengthening the time it takes to access files using function hooking\nI tried adding everything from the previous post's answer, but I decided to stay with printf for output because it was pointed out that std::format makes the exe size large. I also decided to avoid std::filesystem::exists because it causes an 8-10 KB exe size increase.\nTo compile this on Windows, you need to install EasyHook.\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 <format>\n#include <climits>\n// easyhook.h installed with NuGet\n// https://easyhook.github.io/documentation.html\n#include <easyhook.h>\n#include <Windows.h>\n\nvoid getExitInput()\n{\n int ch = 0;\n\n for (; ch != '\\n'; ch = std::getchar());\n\n std::printf(\"Press Enter to exit\\n\");\n ch = std::getchar();\n}\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n WCHAR* dllToInject32 = nullptr;\n WCHAR* dllToInject64 = nullptr;\n _TCHAR* applicationName = argv[0];\n DWORD binaryType = 0;\n BOOL getBinaryTypeResult = GetBinaryType(applicationName, &binaryType);\n\n if (getBinaryTypeResult == 0 || (binaryType != 0 && binaryType != 6))\n {\n std::printf(\"ERROR: This exe wasn't identified as 32-bit or as 64-bit\\n\");\n getExitInput();\n return 0;\n }\n else if (binaryType == 0)\n {\n dllToInject32 = (WCHAR*)L\"load_extender_32.dll\";\n }\n else\n {\n dllToInject64 = (WCHAR*)L\"load_extender_64.dll\";\n }\n\n std::printf(\"Enter the process Id: \");\n DWORD pid = 0;\n std::cin >> pid;\n\n NTSTATUS errorCode = RhInjectLibrary(\n pid, // 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 nullptr, // data to send to injected DLL entry point\n 0 // size of data to send\n );\n\n if (errorCode != 0)\n {\n std::printf(\"RhInjectLibrary failed with error code = %d\\n\", errorCode);\n PWCHAR errorMessage = RtlGetLastErrorString();\n std::printf(\"%ls\\n\", errorMessage);\n getExitInput();\n return 0;\n }\n\n std::printf(\"Library injected successfully.\\n\");\n getExitInput();\n return 0;\n}\n\nload_extender.cpp\n#include <climits>\n#include <mutex>\n#include <thread>\n#include <chrono>\n#include <vector>\n#include <string>\n#include <string_view>\n#include <unordered_map>\n\n#ifdef _WIN32\n// easyhook.h installed with NuGet\n// https://easyhook.github.io/documentation.html\n#include <easyhook.h>\n#include <Windows.h>\nusing wcharOrChar = wchar_t; // file paths are UTF-16LE on Windows\nusing strType = std::wstring;\nusing svType = std::wstring_view;\n#else\n#ifndef _GNU_SOURCE\n#define _GNU_SOURCE\n#endif\n#include <dlfcn.h>\nusing wcharOrChar = char;\nusing strType = std::string;\nusing svType = std::string_view;\n#endif\n\n// using multiple cpp files made exe bigger, so definitions are in this header\n#include \"shared.h\"\n\nstatic MapAndMutex mapAndMutexObject;\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 wchar_t* path = (const wchar_t*)(ObjectAttributes->ObjectName->Buffer);\n int pathEndIndex = (ObjectAttributes->ObjectName->Length) / sizeof(wchar_t);\n int filenameIndex = pathEndIndex;\n\n for (; filenameIndex >= 0 && path[filenameIndex] != '\\\\'; filenameIndex--);\n\n filenameIndex++; // moving past '\\\\' character or to 0 if no '\\\\' was found\n auto it = mapAndMutexObject.fileMap.find(\n svType(path + filenameIndex,\n (size_t)pathEndIndex - filenameIndex)\n );\n\n if (it != mapAndMutexObject.fileMap.end())\n {\n mapAndMutexObject.delayFile(it->second);\n }\n\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 = { nullptr };\n HMODULE moduleHandle = GetModuleHandle(TEXT(\"ntdll\"));\n\n if (moduleHandle)\n {\n LhInstallHook(\n GetProcAddress(moduleHandle, \"NtCreateFile\"),\n NtCreateFileHook,\n nullptr,\n &hHook1\n );\n }\n\n ULONG ACLEntries[1] = { 0 };\n LhSetExclusiveACL(ACLEntries, 1, &hHook1);\n}\n#else\nstatic auto originalFopen = reinterpret_cast<FILE * (*)(const char* path, const char* mode)>(dlsym(RTLD_NEXT, \"fopen\"));\n\nFILE* fopen(const char* path, const char* mode)\n{\n int filenameIndex = -1;\n int pathEndIndex = 0;\n\n for (; path[pathEndIndex] != '\\0'; pathEndIndex++)\n {\n if (path[pathEndIndex] == '/')\n {\n filenameIndex = pathEndIndex;\n }\n }\n \n filenameIndex++; // moving past '/' character or to 0 if no '/' was found\n auto it = mapAndMutexObject.fileMap.find(\n svType(path + filenameIndex,\n (size_t)pathEndIndex - filenameIndex)\n );\n \n if (it != mapAndMutexObject.fileMap.end())\n {\n delayFile(it->second);\n }\n\n return original_fopen(path, mode);\n}\n#endif\n\nshared.h\n#ifndef DEBUG\n#define printf(...) (0)\n#endif\n\nclass FileHelper\n{\npublic:\n FileHelper(const FileHelper& fhelper) = delete;\n FileHelper& operator=(FileHelper other) = delete;\n FileHelper(FileHelper&&) = delete;\n FileHelper& operator=(FileHelper&&) = delete;\n\n FileHelper() {}\n\n ~FileHelper()\n {\n if (_f)\n {\n std::fclose(_f);\n }\n }\n\n void tryToOpenFile(const char* filename)\n {\n#ifdef _WIN32\n if (fopen_s(&_f, filename, \"rb\") != 0 || !_f)\n#else\n if (!(_f = std::fopen(filePath, \"rb\")))\n#endif\n {\n throw \"FileHelper fopen failure in tryToOpenFile\";\n }\n }\n\n bool checkIfFileExists(std::string&& filename)\n {\n#ifdef _WIN32\n bool exists = fopen_s(&_fcheck, filename.c_str(), \"rb\") == 0;\n#else\n bool exists = (_fcheck = std::fopen(filename.c_str(), \"rb\"));\n#endif\n\n if (_fcheck)\n {\n std::fclose(_fcheck);\n _fcheck = nullptr;\n }\n\n return exists;\n }\n\n bool getCharacter(wcharOrChar& ch)\n {\n if (_bufferPosition == _charactersRead)\n {\n _bufferPosition = 0;\n _charactersRead = (int)std::fread(_buffer.data(), sizeof(wcharOrChar), _buffer.size(), _f);\n\n if (!_charactersRead)\n {\n return false;\n }\n }\n\n ch = _buffer.at(_bufferPosition);\n _bufferPosition++;\n\n return true;\n }\n\n void resetFile() // used in tests\n {\n if (std::fseek(_f, 0, SEEK_SET) != 0)\n {\n throw \"FileHelper fseek failure in resetFile\";\n }\n\n _bufferPosition = 0;\n _charactersRead = 0;\n }\n\nprivate:\n FILE* _f = nullptr;\n FILE* _fcheck = nullptr;\n std::vector<wcharOrChar> _buffer = std::vector<wcharOrChar>(8192 / sizeof(wcharOrChar));\n int _bufferPosition = 0;\n int _charactersRead = 0;\n};\n\nstruct MapValue\n{\n std::vector<int> delays;\n size_t position = 0;\n unsigned int fullResetCheckNumber = 0;\n bool reset = false;\n bool resetAll = false;\n\n MapValue(bool& textRemaining, std::vector<int>& delaysVector, FileHelper& fhelper)\n {\n wcharOrChar ch = '\\0';\n long long int delay = 0;\n\n for (\n textRemaining = fhelper.getCharacter(ch);\n ch != '\\n' && textRemaining;\n textRemaining = fhelper.getCharacter(ch))\n {\n if (ch >= '0' && ch <= '9')\n {\n ch = ch - '0';\n delay *= 10;\n delay += ch;\n\n if (delay > INT_MAX)\n {\n throw \"delays can't be larger than INT_MAX\";\n }\n }\n else if (ch == '-')\n {\n if (delaysVector.empty())\n {\n resetAll = true;\n }\n else\n {\n reset = true;\n }\n\n break;\n }\n else if (ch == '/')\n {\n delaysVector.push_back((int)delay);\n delay = 0;\n }\n }\n\n if (delay != 0 && !reset && !resetAll)\n {\n delaysVector.push_back((int)delay);\n }\n\n // make sure to go to end of line\n for (; ch != '\\n' && textRemaining; textRemaining = fhelper.getCharacter(ch));\n }\n};\n\nstruct KeyCmp\n{\n using is_transparent = void;\n\n bool operator()(const svType sv1, const svType sv2) const\n {\n return sv1 == sv2;\n }\n};\n\nstruct KeyHash\n{\n using is_transparent = void;\n\n size_t operator()(const svType sv) const\n {\n return _hashObject(sv);\n }\n\nprivate:\n std::hash<svType> _hashObject = std::hash<svType>();\n};\n\nusing myMapType = std::unordered_map<strType, MapValue, KeyHash, KeyCmp>;\n\nclass MapAndMutex\n{\npublic:\n std::mutex mutexForMap;\n myMapType fileMap;\n\n MapAndMutex()\n {\n try\n {\n std::wstring keyStr;\n std::vector<int> delaysVector;\n FileHelper fhelper;\n std::string filename(\"files_and_delays.txt\");\n size_t fileNumber = 0;\n\n // std::filesystem::exists caused 10 KB exe size increase\n for (\n ;\n fhelper.checkIfFileExists(\"files_and_delays\" + std::to_string(fileNumber) + \".txt\");\n fileNumber++);\n\n if (fileNumber > 0)\n {\n filename = \"files_and_delays\" + std::to_string(fileNumber - 1) + \".txt\";\n }\n\n fhelper.tryToOpenFile(filename.c_str());\n#ifdef _WIN32\n wchar_t byteOrderMark = '\\0';\n\n if (!fhelper.getCharacter(byteOrderMark))\n {\n printf(\n \"files_and_delays.txt byte order mark is missing\\n\\\n make sure files_and_delays.txt is saved as UTF-16 LE\\n\"\n );\n }\n else if (byteOrderMark != 0xFEFF) // not 0xFFFE due to how wchar_t is read\n {\n printf(\n \"files_and_delays.txt byte order mark isn't marked as UTF-16 LE\\n\\\n make sure files_and_delays.txt is saved as UTF-16 LE\\n\"\n );\n }\n#endif\n\n while (addMapPair(fileMap, keyStr, delaysVector, fhelper));\n }\n catch (char const* e)\n {\n char const* resolveC4101Warning = e;\n printf(\"%s\\n\", resolveC4101Warning);\n fileMap.clear(); // clear map so failure is more obvious\n }\n }\n\n bool addMapPair(myMapType& fileMap, strType& keyStr, std::vector<int>& delaysVector, FileHelper& fhelper)\n {\n keyStr.clear();\n delaysVector.clear();\n wcharOrChar ch = '\\0';\n bool keepWhitespace = false;\n bool textRemaining = fhelper.getCharacter(ch);\n\n if (ch == '\\n' || !textRemaining)\n {\n return textRemaining;\n }\n else if (ch == '/')\n {\n keepWhitespace = true;\n }\n else if (ch != ' ' && ch != '\\f' && ch != '\\r' && ch != '\\t' && ch != '\\v')\n {\n keyStr.push_back(ch);\n }\n\n for (\n textRemaining = fhelper.getCharacter(ch);\n ch != '\\n' && ch != '/' && textRemaining;\n textRemaining = fhelper.getCharacter(ch))\n {\n if (keepWhitespace || (ch != ' ' && ch != '\\f' && ch != '\\r' && ch != '\\t' && ch != '\\v'))\n {\n keyStr.push_back(ch);\n }\n }\n\n if (textRemaining && ch == '/')\n {\n MapValue fileMapValue(textRemaining, delaysVector, fhelper);\n\n if (!keyStr.empty() && (!delaysVector.empty() || fileMapValue.resetAll))\n {\n fileMapValue.delays = delaysVector;\n strType keyStrCopy(keyStr);\n fileMapValue.delays.shrink_to_fit();\n keyStrCopy.shrink_to_fit();\n fileMap.emplace(std::move(keyStrCopy), std::move(fileMapValue));\n }\n }\n\n return textRemaining;\n }\n\n void delayFile(MapValue& fileMapValue)\n {\n#ifndef DEBUG // this needs to be reset in the test, so it's a global variable instead\n static unsigned int fullResetCount = 0;\n#endif\n\n printf(\"fullResetCount: %zu\\n\", fullResetCount);\n int delay = 0;\n\n {\n std::lock_guard<std::mutex> mutexForMapLock(mutexForMap);\n\n if (fileMapValue.fullResetCheckNumber < fullResetCount)\n {\n fileMapValue.position = 0;\n fileMapValue.fullResetCheckNumber = fullResetCount;\n printf(\"this delay sequence reset due to prior full reset\\n\");\n }\n\n if (fileMapValue.resetAll)\n {\n if (fullResetCount == UINT_MAX) // this probably won't ever happen\n {\n fullResetCount = 0;\n\n for (auto& it : fileMap)\n {\n it.second.fullResetCheckNumber = 0;\n }\n\n printf(\"fullResetCount reset\\n\");\n }\n\n fullResetCount++;\n printf(\"fullResetCount set to %zu, all sequences will be reset\\n\", fullResetCount);\n }\n else if (fileMapValue.position == fileMapValue.delays.size())\n {\n if (fileMapValue.reset)\n {\n fileMapValue.position = 0;\n printf(\"this delay sequence reset\\n\");\n }\n else\n {\n printf(\"delay sequence already finished\\n\");\n }\n }\n\n if (fileMapValue.position < fileMapValue.delays.size())\n {\n delay = fileMapValue.delays.at(fileMapValue.position);\n fileMapValue.position++;\n }\n\n printf(\"delay is %d millisecond(s)\\n\\n\", delay);\n }\n\n if (delay > 0)\n {\n#ifndef DEBUG\n std::this_thread::sleep_for(std::chrono::milliseconds(delay));\n#endif\n }\n }\n};\n\nload_extender_test.cpp\n#include <climits>\n#include <mutex>\n#include <vector>\n#include <string>\n#include <unordered_map>\n\n#ifdef _WIN32\nusing wcharOrChar = wchar_t; // file paths are UTF-16LE on Windows\nusing strType = std::wstring;\nusing svType = std::wstring_view;\n#else\nusing wcharOrChar = char;\nusing strType = std::string;\nusing svType = std::string_view;\n#endif\n\n#define DEBUG\nunsigned int fullResetCount = 0;\n\n// using multiple cpp files made exe bigger, so definitions are in this header\n#include \"shared.h\"\n\nvoid windowsHookFunction(MapAndMutex& mapAndMutexObject, strType& pathStr)\n{\n if (!pathStr.empty() && pathStr.back() == '\\r')\n {\n pathStr.pop_back();\n }\n\n const wcharOrChar* path = pathStr.c_str();\n\n // in the actual program, this will always be less than INT_MAX\n int pathEndIndex = pathStr.size() < INT_MAX ? (int)pathStr.size() : INT_MAX;\n int filenameIndex = pathEndIndex;\n\n for (; filenameIndex >= 0 && path[filenameIndex] != '\\\\'; filenameIndex--);\n\n filenameIndex++; // moving past '\\\\' character or to 0 if no '\\\\' was found\n auto it = mapAndMutexObject.fileMap.find(\n svType(path + filenameIndex,\n (size_t)pathEndIndex - filenameIndex)\n );\n\n if (it != mapAndMutexObject.fileMap.end())\n {\n#ifdef _WIN32\n printf(\"\\n%ls found in map\\n\", pathStr.c_str());\n#else\n printf(\"\\n%s found in map\\n\", pathStr.c_str());\n#endif\n mapAndMutexObject.delayFile(it->second);\n }\n else\n {\n#ifdef _WIN32\n printf(\"\\n%ls not found in map\\n\", pathStr.c_str());\n#else\n printf(\"\\n%s not found in map\\n\", pathStr.c_str());\n#endif\n }\n}\n\nvoid unixHookFunction(MapAndMutex& mapAndMutexObject, strType& pathStr)\n{\n if (!pathStr.empty() && pathStr.back() == '\\r')\n {\n pathStr.pop_back();\n }\n\n const wcharOrChar* path = pathStr.c_str();\n\n int filenameIndex = -1;\n int pathEndIndex = 0;\n\n for (; path[pathEndIndex] != '\\0'; pathEndIndex++)\n {\n if (path[pathEndIndex] == '/')\n {\n filenameIndex = pathEndIndex;\n }\n }\n\n filenameIndex++; // moving past '/' character or to 0 if no '/' was found\n auto it = mapAndMutexObject.fileMap.find(\n svType(path + filenameIndex,\n (size_t)pathEndIndex - filenameIndex)\n );\n\n if (it != mapAndMutexObject.fileMap.end())\n {\n#ifdef _WIN32\n printf(\"\\n%ls found in map\\n\", pathStr.c_str());\n#else\n printf(\"\\n%s found in map\\n\", pathStr.c_str());\n#endif\n mapAndMutexObject.delayFile(it->second);\n }\n else\n {\n#ifdef _WIN32\n printf(\"\\n%ls not found in map\\n\", pathStr.c_str());\n#else\n printf(\"\\n%s not found in map\\n\", pathStr.c_str());\n#endif\n }\n}\n\nvoid printMap(const myMapType& fileMap)\n{\n for (auto& it : fileMap)\n {\n printf(\n#ifdef _WIN32\n \"%ls : fullResetCheckNumber %zu : position %zu : \",\n#else\n \"%s : fullResetCheckNumber %zu : position %zu : \",\n#endif\n it.first.c_str(),\n it.second.fullResetCheckNumber,\n it.second.position\n );\n\n for (size_t i = 0; i < it.second.delays.size(); i++)\n {\n printf(\"%d / \", it.second.delays.at(i));\n }\n\n if (it.second.reset)\n {\n printf(\"RESET\");\n }\n else if (it.second.resetAll)\n {\n printf(\"RESET ALL\");\n }\n\n printf(\"\\n\");\n }\n}\n\nvoid testFunctions(MapAndMutex& mapAndMutexObject, FileHelper& fhelper, bool testUnix)\n{\n strType pathStr;\n wcharOrChar ch = '\\0';\n\n while (fhelper.getCharacter(ch))\n {\n if (ch == '\\n')\n {\n if (testUnix)\n {\n unixHookFunction(mapAndMutexObject, pathStr);\n }\n else\n {\n windowsHookFunction(mapAndMutexObject, pathStr);\n }\n\n printMap(mapAndMutexObject.fileMap);\n pathStr.clear();\n }\n else\n {\n pathStr.push_back(ch);\n }\n }\n\n if (testUnix)\n {\n unixHookFunction(mapAndMutexObject, pathStr);\n }\n else\n {\n windowsHookFunction(mapAndMutexObject, pathStr);\n }\n}\n\nvoid testInputs(MapAndMutex& mapAndMutexObject)\n{\n FileHelper fhelper;\n fhelper.tryToOpenFile(\"test_input.txt\");\n wcharOrChar byteOrderMark = '\\0';\n#ifdef _WIN32\n\n if (!fhelper.getCharacter(byteOrderMark))\n {\n printf(\n \"test_input.txt byte order mark is missing\\n\\\n save test_input.txt as UTF-16 LE\\n\\n\"\n );\n\n return;\n }\n else if (byteOrderMark != 0xFEFF) // not 0xFFFE due to how wchar_t is read\n {\n printf(\n \"test_input.txt byte order mark isn't marked as UTF-16 LE\\n\\\n make sure files_and_delays.txt is saved as UTF-16 LE\\n\\n\"\n );\n }\n#endif\n printf(\"\\ntesting UNIX\\n\\n - - - - - - - - - -\\n\\n\");\n printMap(mapAndMutexObject.fileMap);\n testFunctions(mapAndMutexObject, fhelper, true);\n printMap(mapAndMutexObject.fileMap);\n fullResetCount = 0;\n fhelper.resetFile();\n#ifdef _WIN32\n fhelper.getCharacter(byteOrderMark);\n#endif\n\n for (auto& it : mapAndMutexObject.fileMap)\n {\n it.second.position = 0;\n it.second.fullResetCheckNumber = 0;\n }\n\n printf(\"\\n\\ntesting Windows\\n\\n - - - - - - - - - -\\n\\n\");\n printMap(mapAndMutexObject.fileMap);\n testFunctions(mapAndMutexObject, fhelper, false);\n printMap(mapAndMutexObject.fileMap);\n}\n\nint main()\n{\n try\n {\n printf(\"\\ntest start\\n\\n\");\n MapAndMutex mapAndMutexObject;\n testInputs(mapAndMutexObject);\n }\n catch (char const* e)\n {\n printf(\"%s\", e);\n }\n\n printf(\"\\ntest finished, press Enter to exit\\n\");\n char ch = getchar();\n\n return 0;\n}\n\n" |
Class
class Player {
std::string name;
int score;
int id;
};
I thought about how to write a code to sort and search vector of these classes by three criteria: name, id, and score.
The search what I want is to output the previous value and next value of the found element.
The cod... |
I implemented a simple tokenizer. Would love to hear your feedback on code style, best practices:
#include <stdio.h>
#include "lexer.h"
#include "mem.h"
static inline int delimiter(char c);
char **lexer_tokenize(const char *s) {
char **rv, **tmp;
int i, j, k, len, cap;
cap = 4;
rv = mem_malloc(sizeo... |
From scanf() to fgets(), we need to first specify the maximum length of the string input, due to which input gets a limitation, which isn't that good. As input can vary from [0, ∞), due to computer limitation input will never reach ∞, but it can be very large.
I have seen in C++, there no limit for string input.
std::s... |
I have written an isPalindrom-Function in TypeScript.
const isPalindrom = (word: String): boolean => {
const mid = Math.floor(word.length / 2);
for (let i = 0; i < mid; i++) {
const left = word[i].toLocaleLowerCase();
const right = word[word.length - 1 - i]
.toLocaleLowerCase();
... |
I would like to generate list of vertices and normals (with the correct indices) for rendering a cylinder barrel (I ommited the end caps for brevity).
The normals should not be interpolated (flat shaded cylinder), so all four vertices that form a radial segment must have the same normal.
Currently this is achieved by f... |
Function:
This is to calculate the values for the equation:
$$\rho = \frac{m}{v} = \frac{mass}{volume}$$
what I need help with:
I still can’t get my head around classes and want to know if I’m doing them right any suggestions are most welcome.
Code:
from decimal import Decimal
from dataclasses import dataclass
@datacl... |
I'm just wondering if there is a better way of executing multiple methods depending on a value?
I have a Property that gets the NumberOflegs. NumberOfLegs can have a value between 1-6. If the value is 1, it needs to execute InsertLeg1Details. If the value is 2, it needs to execute InsertLeg1Details and InsertLeg2Detail... |
I am trying to cleanup a dataframe (and the code) in Pandas.
I used to use the modin library before but I have since switched from Win 10 to Win 11 and none of ray and dask libraries work on Windows 11 and I have raised an issue with respective repositories.
In the meanwhile, I am intending to use multiprocessing as an... |
I'm working on an implementation of binary search (in Python) that can operate on a sorted array that may have duplicate elements.
I've written a submission that has managed to hold up against my test cases so far, but I have the feeling that there may be a more elegant way to write my recursive solution.
If anyone has... |
Refer to Wikipedia English for more context on Wordle.
This version behaves exactly like the standard Wordle game, except that it displays all possible choices in the current condition on the left side.
It accepts keyboard inputs, backspace to delete a letter, enter to confirm, and you can also select a choice from the... |
Given two hashes, my script generates two (poorly formatted) C# source files containing some classes that represent several AST nodes a programming language needs and an implementation of the Visitor pattern for each. While I care a lot about the formatting of my Raku code, the formatting of the C# output is of no part... |
I want to use my Web Scraper to get all tweets about Apple up to a date I specify. At the moment I'm scraping the tweets of today, or the last few days. However, my goal is to scrape all tweets from the last 3 years. When I run my code it takes hours for only a period of a few days. Does anyone have any tips for me on ... |
public string Get()
{
string cleaned = Number.Trim().Replace(".", string.Empty).Replace("-", string.Empty).Replace("_", string.Empty).Replace(" ", string.Empty).Replace(",", string.Empty);
return cleaned.Substring(0, 2).ToUpper();
}
How could the .Replace(".", string.Empty).Replace(... and ToUpper be written u... |
Code is posted after explanation.
Due to the size of the project, this is being posted in three separate posts. This also ensures each post is more focused.
Post 2 of 3, CLI: Newspaper Bill Calculator CLI with Python (2 of 3, CLI)
Post 3 of 3, Database: Newspaper Bill Calculator CLI with Python (3 of 3, Database)
Wh... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.