instruction
stringlengths
71
95.1k
I'm writing some code to take high precision timings of a function call for (int i = 0; i < iterations; i++) { beginTime = high_resolution_clock::now(); CallFunc(functionPtr, otherParamaters ...); // inline function call to do the timed function endTime = high_resolution_clock::now(); elapsedTime = d...
In my BlogList.vue component I made a search input field: <input type="text" placeholder="Enter key word ..." v-model="search"> And a computed property: computed: { getfilteredData() { return this.blogs.filter(blog => blog.name.toLowerCase().includes( this.search.toLowerCase() ) || ...
I have these 3 methods for ATM mock program. public decimal CheckBalance(BankAccount account) { return account.AccountBalance; } public void Deposit(BankAccount account, BankTransaction bankTransaction) { account.AccountBalance += bankTransaction.TransactionAmount; } public...
I have a simple macro moving data from Teradata to Excel. The process normally takes me 10 minutes to perform manually, however the macro can run for hours sometimes. This is making the macro seems counterproductive. But I still want to give it a chance. Manually, I would just simply paste the sql to teradata, and copy...
I would like to arrange a system messages dictionary for an application in JavaScript. As an initial intention, I thought something about the following structure: export const SYS_MESSAGES = Object.freeze({ fileSizeExceeded: { code: "FILE_SIZE_EXCEEDED", text: "The file size exceeds allowed limit" ...
I have started to use C# 7's type based pattern matching. A method that only manages a single pattern-based result looks very clean and is easy to reason about. However, once a second pattern-based result that depends on the first pattern-based result creates an arrow anti-pattern, and will only get worse with n-result...
I have an array of the form (3x3 case as an example) $$A = [a_{11}, a_{12}, a_{22}, a_{13}, a_{23}, a_{33}] $$ corresponding to the symmetric matrix $$\begin{pmatrix} a_{11} & a_{12} & a_{13}\\ a_{12} & a_{22} & a_{23} \\ a_{13} & a_{23} & a_{33} \end{pmatrix}$$ I want to print out this very matrix (in general of size ...
I 'm new here. I wrote the following django code. I 'm opening, closing files here and saving them temporarily and deleting them. I tried to use Python's tempfile and was getting Permission Error and I did asked about it on IRC #django but maybe Windows is not a pleasant to use OS for programmers so I couldn't get a go...
I am (relatively) new to game programming and have been exploring creating an entity component system for my simple 2D game engine. Here is what I have so far: Entity.h #pragma once using Entity = int; ComponentArray.h #pragma once #include "Entity.h" #include <unordered_map> class ComponentArrayAbstract {}; templ...
I had an assignment last semester to program a payroll app utilizing methods. I went back to it and re-wrote it to include an extra class as well. I would like some feedback regarding whether my code is following the Single Responsibility SOLID principle - should the class be split further into more classes? I would al...
So I'm currently using python to unscramble words that are retrieved from an OCR program (pytesseract). The current code I am using to unscramble words is this: import numpy as nm import pytesseract import cv2 import ctypes from PIL import ImageGrab def imToString(): # Path of tesseract executable pytes...
I have a class that imports the FX Rates produced by another department. This works as intended, which is to return a Pandas DataFrame with all FX Rates by month. The DataFrame it returns is then used by another 5 classes, that basically import other files and do some formatting and calculations with their own columns,...
I want to fill an array of strings with the name of each directory item. The issue is allocating memory. I either need to count the items before, allocate memory, then go over them again, or I will have to reallocate each iteration of the while loop. Both of these options seem slow. Surely there's a better way. Which i...
I have a couple questions about this program Should I implement runnable instead of using thread class? I like the idea of the consumer and producer being thread objects, it seems simpler to me, but I have seen people argue the benefits if runnable interface. Are static methods in the main class considered good/bad c...
I want to fill an array of dirent pointers with each entry of a specified directory. I either need to count the items before, allocate memory, then go over them again, or I will have to reallocate each iteration of the while loop. Both of these options seem slow. Surely there's a better way. Are these my only option: s...
Here I'm posting my code for the Reorganize String problem on LeetCode. If you have time and would like to review, please do so, I'd appreciate that. On LeetCode, we are only allowed to change the argument names and brute force algorithms are discouraged, usually fail with TLE (Time Limit Error) or MLE (Memory Limit Er...
I have a writeOnFile() method with too many fwrite(). I think it is not a good implementation because too many system calls may produce a high overhead. What can I do? Code void writeOnFile() { char cr[1] = {'\n'}; //Usefull characters char sp[1] = {' '}; char header1[] = "Instant "; ...
Hi :) I am a beginner coder who just learnt C++ and I wanted to apply it in projects to solidify my learning process. However, I only took a short tutorial before trying this out hence I'm pretty unsure about my C++ coding practices and I would like to know what areas I can improve on - and perhaps what kind of resourc...
Python3 - Recursive XML Files to Large Text File I have a recursive function that looks through a directory (there are 6000+ files). For each XML file found - the XML is converted to a string and appended to an array. At the end of the recursion - All these arrays are joined to return a (very) large string. The error I...
I am learning about clean and maintainable code. I heard that functions should be no more than 20 lines long (preferably 5 - 10 lines). I have come across this Bob Martin quote where he said: “The first rule of functions is that they should be small. The second rule of functions is that they should be smaller than tha...
I've written the following custom event system module and I'm planning to use it in production in the future. Before I do that, I'd like to ask for general suggestions on how to improve it. Thanks a lot. const event = (function() { let registry = {}; function on(event, callback) { if(!registry[event]) registr...
I have the code below, which works successfully, and is used to parse, clean log files (very large in size) and output into smaller sized files. This would take about 12-14 mins to process 1 GB worth of logs (on my laptop). Can this be made faster? Could Dask or parallelism or asyncio or another help speed this up? I a...
I wanted to create an AES encryption service which will use a custom key/iv. I want 2 methods: dycrypt/encrypt byte[] The code works as expected, any remarks/issues? public class AesGenericEncryptionService { private readonly byte[] m_Key; private readonly byte[] m_IV; public AesGenericEncryptionService(by...
For self learning purpose, I have created some xUnit unit test for these 2 Atm classes. At the moment, data is store in the in-memory object. This version is extended from previous version. For brevity, I excluded Withdraw method and ThirdPartyTransfer public class BankAccount : IBankAccount { public int Id { get; ...
I am using c++17 and wide characters. I have created a function to create a wchar_t* using a variable number of parameters ... #include <stdarg.h> // the caller will free the memory wchar_t* GetMessage( const wchar_t* format, ... ) { va_list args; va_start(args, format); // get the size of the final string co...
The task is to represent a Matrix as a class and to instantiate it from a string such as "1 2 3 4\n5 6 7 8\n9 8 7 6" The class must provide methods for accessing individual rows and columns by index starting at 1. While my solution is relatively short and more or less clear, I'm wondering about the ways to make it bett...
I did the Nth Prime problem on exercism.io. Now I need feedback what can be done better / improved to make the most of rust. The code calculates the nth prime. I chose to provide the sieve of Eratosthenes as iterator in Rust. The code can be seen here: https://exercism.io/tracks/rust/exercises/nth-prime/solutions/22ef0...
Here I'm posting my Java code for the skyline problem. If you have time and would like to review, please do so, I'd appreciate that. Problem A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Now suppose you are given the locations and height o...
I am working on the Project Euler, number 3 project (finding the largest prime factor of 600851475143), but I wanted to take it a step further and write something that will list all factors and prime factors of any inputted number. I'm also using this project to learn about classes (I'm putting all my different Proj. E...
I'm going through the eBook Intro to App Development with Swift by Apple and I am making the Rock, Paper, Scissors app in lesson 20. This is the assignment that I got: [...] Name the enum Sign. Add a calculated property to give the emoji that represents the Sign. [...] You need to be able to compare two Sign instances...
It's a simple timed event template class. It's used in a 3D multiplayer game! template <class T> class CTimeEventDecorator : public CBaseDecorator, public CPooledObject<CTimeEventDecorator<T>> { public: typedef CTimeEvent<T> TTimeEventType; typedef std::vector<TTimeEventType> TTimeEventContainerType; CTime...
I've made this Function gradient() that returns a list of rbg of all the colors in an order. Issues:- What should be the condition for while loop to stop the loop. Though b == 0 in the last elif block works fine. How can I reduce the code of the function keeping the functionality the same. Like if there is any better...
I am trying to create a navbar menu from JSON data. Actually I have achieved it but I am looking for feedback not to call getItems twice? How can I improve my code? Thank you var _ = require('lodash'); let menuConfig = [ { ID: 1, TAG: "M:A", PARENT_TAG: "MAIN", TITLE: "A Title" ...
This is my implementation of Quick Sort Algorithm : def quick_sort(sequence): if len(sequence)<= 1: return sequence else: pivot = sequence.pop() # To take the last item of "sequence" list greater =[] lower = [] for n in sequence: if n > pivot : gre...
I want to pass the param from the request on the scope method in the model and serve it as json to be rendered by select2. Which is better? 1. Pass request from the controller like this controller: public function selectJson(Request $request) { $request = Customer::getSelect2($request) return \Response::json...
Now ALL of the below works as intended - a poll asks users questions and I store them in a dictionary, finally I print how many times a country was mentioned - boring I know. However, I really want to know if there is better, cleaner even high level way to do this (reading comments here people usually mention speed, ef...
This particular snippet is a simple to-do app that allows the user to add new items to the list, mark them as done, delete a single item, or delete all items. What I would be looking for advice on are my use of a function constructor. It may be overkill for something like this, but it is more of a learning exercise to ...
A trie for handling strings for an autocomplete dictionary. This passes my fairly casual tests, though it's always possible that there are broken edge cases, but I'm mainly concerned about design and efficiency: is this a sensible way to implement this data structure? (In particular, is it sensible to do the insert m...
I am attempting to make an unbeatable Tic Tac Toe game using a simplified minimax algorithm. The code looks like this: private static int findBestMove(String[][] board, boolean comp) { // comp returns true if the computer is the one looking for the best move // findBestMove is always called by the program as fi...
I have difficulties when sometimes a game client sends a list of packet in the same buffer, where it is split before processing. The biggest problem is when any packets don't come complete. For example; all packets have the same size, of 1000 bytes, and then we receive a list of packets of only 2500 bytes. Say the thir...
I have these strings: )hello( this has ]some text[ flip }any{ brackets even with )))]multiple[((( brackets As you can see, the brackets are all in the wrong direction. I have a function called flipBracketsDirection() to handle each scenario. Here is an example of input and output of the above strings: flipBracketsDire...
I'm doing some toy problems in a variety of languages and wanted to do the following in Racket Lisp. Given a sorted integer array nums, where the range of elements are in the inclusive range [lower, upper], return its missing ranges. 0, 1, 3, 50, 75 Lower: 0 Upper: 99 Expected Output: ["2", "4->49", "51->74", "76->99...
Here is my code that check and upload an image to my website. Is this code really secure against uploading of malicious codes? Anything I have to add to this code to make it more secure? I have also blocked execution of PHP in images folder using php_flag engine off in .htaccess of images folder, I can also move image...
Good day! I would like to know if this is possible to be refactored into a cleaner code. The reason I'm doing it like this is to catch the column that the error appeared on and then potentially output the column name and value for the client to view later on. // Make the name act as the key and the value equates to ID ...
I need to have a range selector that accepts string values instead of integer value. This is not possible with standard HTML, so I needed to simulate one by using (hidden) radio buttons that are coupled with the range selector and change the label of the range selector accordingly. My code is a bit of a mess, though. C...
I am hoping that someone can take a look at my implementation of a lock-free ring buffer and critique the implementation. I'm hoping that the focus can be of the correctness of the atomic operations and thread safety. The buffer is implemented as a single producer/single consumer ring buffer, and owes a lot of boost's...
Stack Exchange provides access to query their MS SQL databases. They have a table Posts where each post is either a question or an answer (see the schema on right hand side here). I saw a query for questions answered by more than three 50k users: SELECT DISTINCT Q.Id AS [Post Link], Q.AnswerCount FROM Posts Q JOIN Post...
So this is a post as per request in a different post on stack overflow: https://stackoverflow.com/questions/62412713/why-does-my-c-sharp-xml-code-only-work-when-i-enumerate-variable-enumerable. The goal of this code is to re-format an XML-file containing a treeview of a sort of folder structure. The XML is of the follo...
Project structure without code: Packages: Classes in packages: In ConfigConstants I store path to folder, where I save pictures. Also in WebConstants I store URL of Servlet. Here is mySQL script for creating db: drop database meme_exchanger; CREATE SCHEMA `meme_exchanger` DEFAULT CHARACTER SET utf8 ; use meme_exch...
I want to abstract some code which does a bunch of checks and returns a boolean - since I am using the business logic in several places. But I also want to get back the reason why, if it was returned FALSE. I have this in mind... class ContactCanBeContactedCheck { public $not_contactable_reason; const REASON_D...
I have built a COVID model using UVA data. Currently that data is unavailable so I'm using another source. The new source is, of course, a different format. So rather than refactor all of my model macros, I'm formatting the new data in the old format on import. The new data looks like this: The xlsx files go out to co...
Our C++ professor told us to practise the use of std::function, lambda and pointers to functions. He asked us to: Write the function std::function<bool(float)> interval(float low, float high). The function should accept two values low and high and should return a function. The function returned will check if it's par...
I came up with a way to get a dict of distinct elements in a list pointing to the location of each element; it works, but I feel pretty awful about this code, it's very ugly. Is there a more natural/pythonic way to do this? from itertools import groupby sample_data = [1,2,3,3,1,0,5] give_groups = lambda dta: {item: lis...
Can someone please review the code and suggest any improvements / changes? Note that this method works but wanted to see if there is a better way for self learning purpose JavaScript/jQuery. Example https://jsfiddle.net/tjmcdevitt/Lx0vnb89/4/ var AppType = [ ['All'], ['API'], ['AWS'], ['Web'] ]; $....
Problem/Background: I want to support only some special Unicode characters for my program (Greek letters and some math operators). C++ provides a char type, which is always 1 byte in size, however, this is too short to display all characters. Normally this is solved by choosing an encoding like UTF-8 (or 16/32). Howeve...
The question is about printing alphabets in a rangoli pattern of size/dimension input by the user. Example: size 3 ----c---- --c-b-c-- c-b-a-b-c --c-b-c-- ----c---- The picture contains details about the challenge OR https://www.hackerrank.com/challenges/alphabet-rangoli/problem Sample Code: n = int(input('Enter a si...
I have created a function that converts from UTF-16 to UTF-8. This function converts from UTF-16 to codepoint firstly, then from codepoint to UTF-8. void ToUTF8(char16_t *str) { while (*str) { unsigned int codepoint = 0x0; //-------(1) UTF-16 to codepoint ------- if (*str <= 0xD7FF) { ...
I have written a simple fibonacci function in Haskell that uses the State monad to save solutions to overlapping sub-problems. Now despite the function working I am not really happy with the solution, especially with the last map lookup. How can I improve my solution? Thank you. module Lib ( fib ) where import Con...
Early today, I gave an answer to someone where I recommended using IReadOnlyList<T>. Then I was asked why not just use a private setter, e.g. public IList<T> { get; private set; }? This was not an entirely unexpected question. I provided a small example as an update to my answer. However, my example really did not ...
I've seen some other implementations of cat (even in Rust) on this site, but none attempted to completely implement the GNU cat CLI as far as I can tell. This version that I am developing is complete (minus the -u parameter that is ignored by GNU cat anyway) and, as far as I can tell, works. Some problems: It requires...
I am trying to callback C++ class methods from C. Now I have got something working, but am not sure if this is the best solution. I am looking for feedback, as to if there is something wrong with this approach, and how could I make this better. So, here goes my code: This is the C++ class Foo. The class has the methods...
I have question about scope yesterday, and someone gives an answer to don't return anything in scope. Is return something in scope really bad practice? Should I not return anything in the model except query? Rather than scope, I want to create a normal method to return the select2 format. I have so many model/table th...
I'm wondering whether there is a way to make this even more efficient or reduce the number of variables. import random numberOfStreaks = 0 results = [] head_streak = ['H'] * 6 tail_streak = ['T'] * 6 sample_size = 1000000 for i, experimentNumber in enumerate(range(sample_size)): # Code that creates a list of 100 'h...
So as a starter Java project I decided to web scrape some data (specifically all historically No. 1 ranked players for weeks starting from 1973) from the ATP website, and do something with it (IPR). I'm in the process of refactoring my working web scraper and wanted some feedback. Currently my scraper retrieves the No...
Date Detection: Write a regular expression that can detect dates in the DD/MM/YYYY format. Assume that the days range from 01 to 31, the months range from 01 to 12, and the years range from 1000 to 2999. Note that if the day or month is a single digit, it’ll have a leading zero. Then store these strings into variables ...
I am using dropzone and XLSX to load excel documents and then convert them into json. The goal is to upload as many documents as possible and it will create an object with a key of the file name and then the value as the data. The problem I notice is that reader.onload is not available immediately after calling readAsA...
I have put together this f# code in an attempt to solve the following problem Given a mapping operation that may not be able to return a value Cease mapping over the remaining items of a sequence if the mapping operation fails Append the error to items already mapped and return early This cannot be achieved with the ...
I have the code below, which works successfully, and is used to parse, clean log files (very large in size) and output into smaller sized files. Output filename is the first 2 characters of each line. However, if there is a special character in these 2 characters, then it needs to be replaced with a '_'. This will help...
Below is a constexpr circular queue whose size is fixed. From what I tested the code seems to work exactly as expected of a queue. One advantage is how there's no dynamic allocations, so ignoring the hopefully low chance that there are errors in the logic, are there any suggestions to improve this code's performance? C...
I often copy things from my terminal to other places (like Discord), and to make my workflow even easier I decided to use the IPython API to make an extension that has two magic functions pickle and clip. clip can copy the contents of a line (or cell). It can copy both, the input line or the output line. pickle takes i...
I've started learning Lisp one more time (I seem to do this every couple years); my experience is with C, basically. I attempted to solve the Project Euler problem 1: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all th...
Just would like to ask if these custom web API naming follow best practice? Below are some of the web API methods I have created for my pet project using ASP.NET .NET Framework 4.7. I understand that the standard CRUD naming convention especially when I use the scaffolding option. For example, this Cart controller web ...
I created a function that takes a dictionary as parameter. This dictionary is expected to have lists as value pair. (i.e. {1: [1, 2, 3], 'a': [4, 'b', 5, 'c']} ) This function has to return the key associated to the biggest list in the dictionary, or None if the dictionary is empty. (considering the above example, it w...
I would like some advice on efficiency and ways to further remove redundant code. Regex Text File Search: enter a valid directory path, and a string to search for makes a list containing all the matched paths, and a dictionary with the matches of the matched paths get a list of all the text files and go through them...
I've been trying to build an ORM. I started with the connector layer, which is responsible for the database server connections and executes raw SQL as the code below shows. I have built the _dbconnect decorator to separate database connection procedures from the CRUD functions. This will be responsible for SQL conversi...
What are some ideas or ways that I can increase the efficiency of this gravity script because it is way to depending for what i want it for. The game has a target at the center and there are objects far away all around the target and when gravity script is enabled I create an overlap sphere check which objects have a r...
I am building an Android quiz app. I want to display a progress bar showing how many questions a user has answered correctly and how many they have left. Questions are split by difficulty level; easy, medium and hard. All my questions are stored in an SQLite database. The questions table is made up of three columns: le...
I've implemented Many-To-Many relationship and wonder if this is the optimal way for it. Since I do not have extensive EF Core experience I would love if someone with more experience could check it out. Scenario: Many users Many organizations User can belong to multiple organizations Organization can hold multiple use...
I want to create a very big gigantic PNG image. The image pixel are generated randomly, being How can I improve the below code to create a fast random pixel image in java? import java.io.File; import java.io.IOException; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; public class RandomImage { ...
I am wondering, how can I improve this simple MissingResource exception class? I am using it in my simple game. template <typename Resource> class MissingResource : public std::exception { std::string_view fileName{}; std::string_view msg{}; public: MissingResource() = default; MissingResource(std:...
My answer to Project Euler problem 3 (largest prime factor of 600851475143) is below. Please suggest improvements, style changes, indentation, commenting, naming of "objects", ... (defun factors (n) "return a list with prime factors of n" (let ((result)) (loop while (zerop (rem n 2)) ; do 2 ...
I'm posting my C++ code for LeetCode's Expressive Words. If you have time and would like to review, please do so. Thank you! Sometimes people repeat letters to represent extra feeling, such as "hello" -> "heeellooo", "hi" -> "hiiii". In these strings like "heeellooo", we have groups of adjacent letters that are all t...
Here's what I trying to do: Given a paginated API, get all the resources using parallel requests. The API returns a limited number of resources per call. So, you need to use an offset parameter to get to the next set of data until all data is extracted. Here's my idea (but getting some warning because I'm using flat on...
I recently have been ̶w̶a̶s̶t̶i̶n̶g̶ spending my time on making a web scraper specifically designed for FanFictions from fanfiction.net (Okay, I'll admit, I like reading them in my spare time that I should spend with coding) I wrote it so I could read FanFictions offline. (For a Raspberry Pi E-Paper reader, but that'...
I am building a social network with PHP, HTML and CSS and a bit of JS. I want to know how secure my login and register code is. Register html: <input id="uname" type="text" onblur="this.value=removeSpaces(this.value);" name="username" required placeholder="Username..."><p/> <br> <input id="pww" type="pa...
import random # Variables, lists, tuples, and dictionaries. nucleotides = ("A", "C", "G", "T") rev_compliment = {'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G'} seq = "" description = "" frames = [] proteins = [] RNA_codon_table = {"UUU": "F", "CUU": "L", "AUU": "I", "GUU": "V", "UUC": "F", "CUC": "L", "AUC": "I", "GUC": ...
I've made a very simple tile editor. I'd like for someone to review my code and tell me what I could improve on. For example I'm bad at input management and creating systems that work nicely. Say I want to add a way to pick what file it saves to by typing in the file path after a keypress. How do I stop my program ...
I'm posting my C++ code for LeetCode's Evaluate Division. If you have time and would like to review, please do so. Thank you! Problem Equations are given in the format A / B = k, where A and B are variables represented as strings, and k is a real number (floating point number). Given some queries, return the answers. ...
I'm really new to OpenCV. :) I have been working on this for almost an entire day. After hours of sleepless work I would like to know if I can further improve my code. I have written some code to select only the black markings on the images. These black markings are child contours. Whilst my code is able to select some...
Here are my class library code which create credit card. public abstract class CreditCard { public CardType CardType { get; protected set; } public decimal CreditLimit { get; protected set; } public decimal AnnualCharge { get; protected set; } } public class GoldCreditCard : CreditCard { private GoldCr...
I have an api end point which returns the paginated result, the corresponding code for that is as below: public Task<PaginatedDataResult<ProductSearchResult>> GetPaginatedSearchAsync(int currentPage, int perPage, ...
I made this random password script. It works, but i think it is kind of bloated. The part where random characters are being added is the area where I think it needs work. I don't want to declare if and else statement for every combination of lowercase list, uppercase list and digits list(I am taking input from user whe...
I just finished writing an implementation of the "singly linked list data structure",and i wanna know if there are some bugs or memory leaks or any bad code to make the code better! i'm so sorry because there is no comment(But the code is simple , you can understand it) #include <iostream> template<typename T> struct ...
Can I improve on this any further. Is there a prettier way of passing the array sizes? #include <stdio.h> void matrix_addition(size_t n, int A[n][n], int B[n][n], int C[2*n][2*n], size_t c_start, size_t c_end) { for(size_t i = 0; i < n; ++i) { for(size_t j = 0; j < n; ++j) { C[i+c_start][j+c_en...
The code works as intended but I believe it is very inefficient. The calculation of weights is simple, but I imagine this would be silly, for example, a 100 asset portfolio. The first problem is that my code returns to the beginning of the loop if the weight for y is entered incorrectly. Help with this would be amazing...
I am solving the following Hackerrank problem: Climbing the Leaderboard. The problem statement: Alice is playing an arcade game and wants to climb to the top of the leaderboard and wants to track her ranking. The game uses Dense Ranking, so its leaderboard works like this: The player with the highest score is ranked n...
I use TinyMCE with responsivefilemanager and I wanted to know that is my code well-written maintainable and readable, Sorry If this sounds like a stupid and basic question because this is such a basic thing to do, and I have also been in web dev for a long time but I am new at WYSIWYG editors and TinyMCE. Here is my fi...
I am writing an array-like data structure for types other than 8 16 32 64 – the usual type sizes. Ideally, my interface is the following for addressing the array. void setindex(uint8_t *array, size_t width, size_t index, uint64_t value); uint64_t getindex(uint8_t *array, size_t width, size_t index); This is basically ...
The program is to get the nearest prime number to a number while adding a number. I solved the problem but I wish to optimize the code. import time def isprime(a ,d): b=a c=0 f=b**(0.5) for i in range(1,int(f)+1): if a%i==0 and c<=1: c+=1 if c==1: return d.append(b) e...
I am using PHP for detecting a user's IP address and displaying their details, and I use OOP (i.e. object-oriented programming). Are there any problems in it or is it well-written? index.php: <?php require('UserInfo.php'); ?> <!DOCTYPE html> <html> <head> <title>UserInfo Demo</title> <style> table { margi...