instruction
stringlengths
71
95.1k
I wrote my first series of test for this simple function: def map_directory(self, path='', method='recursive'): """ scan the given path method -> recursive (all levels) or single (first level only) :param method: string :param path: string :return: generator """ if not path: ...
Over the last few days I created this Pig Latin Translator just for fun. I would really appreciate it if anybody could give suggestions of how to improve the code and make the program more efficient. Here is the GitHub link for the project. For anybody who doesn't know the Pig Latin, feel free to look at the README, wh...
Which is good to use and why? if ($a == 3) { //do something } Or if (3 == $a) { //do something }
I am trying to write a Linked List implementation that can insert and delete at either head or tail in constant time. I think I have it working, but I was curious what improvements I could make to this code? Additionally, is there a way to delete from the tail in constant time without having a doubly linked list? p...
This code allows you monitor the progress of the Powershell Jobs you just started. One of the key features is the ability to stop the other Jobs when 1 is failed. For example, if you are running some Jobs with a runtime of around 60 seconds, the results needs to be combined to be of any use, Job 2 failed at 20 seconds....
I just implemented binary search tree as described in Cormen's algorithm book. I'm not interested in correctness or performance of the implementation. I'm looking for reviews, comments on code style and suggestions on what can be done to improve readability of the code and make it more concise, or any general issues yo...
I want to parse a CSV file and store the data using the istream >> operator but I am running into big performance issues. Here is the current version: #include <vector> #include <sstream> #include <fstream> #include <string> #include <iostream> template <class T> class CSV { std::vector<std::vector<T>> _data; ...
Any improvements that I can make with this code? Also, is there another way to convert a vector to a string variable without using a for ranged-based loop? From the posts I've seen for converting, I only saw printing the vector instead of returning a string. #include <string> #include <vector> #include <sstream> #inclu...
I want to design Chinese mapping number routing. How can I improve this code in the method mapRouting? I want to use reflect auto get method name by providing a value without if else, but I have no idea how to do it. public class FwMappingChi { public static Map<String, String> mapRouting(String mapName){ ...
Here is how to transform a Zorglub (it is an API that I can not modify): Zorglub transformedZorglub = zorglub.transform() I am given a java.util.List<Zorglub> and I must transform them all, then afterwards I will perform more operations on the transformed Zorglubs. After transformation I never use the originals anymor...
I was asked to give more context. So here we go. We want to create some HTML in code behind to add an "add" and a "refresh" button to a grid view header column. Approach #1 does this using string concatination to produce the necessary HTML, whereas approach #2 uses .NET objects to create exactly the same HTML. This tim...
Following task: Customer-data, given in a JSON-file, have to be completed with additional address-data. Given in a second JSON-file. Then these data-stock has to be saved into a MongoDB-database. Schema of the customer-JSON: [ { "id": "1", "first_name": "Ario", "last_name": "Noteyoung", "em...
Here is my code to find the details of the domain. The domain can be feed as following: bash script.sh domain1.com domain2.com bash script.sh domains.txt <-- not completed The output should be in following format: IP Address: 192.168.101.2 Server Name: servername.com NS1: ns1.ournameserver.com NS2: ns2.ournameserver.c...
I am new to jquery and implemented following function in a js file in case of error- function before_submit_check_if_has_blank_field() { $("[type=submit]").click(function(e) { var of_key_field = $('.key_field') var of_val_field = $('.val_field') var should_run = 1 if (of_key_field.l...
I am new to java, and to programming as a whole. trying to become a self taught programmer. i read books and solve exercise. the issue i face is lack of feedback. any comments on this piece of code is appreciated : /* * Quadratic.java * ------------------ * calculates the solutions of a quadratic equation (a*x^2 + b...
I have written the following program: Math Quiz. It is a programming exercise number 5 chapter 6 from the book "Art and Science of Java". The program seems to be working. However, I would be grateful for any suggestions on any areas that I can improve on (any bad habits etc.). I am also intrested if there are any mor...
Given this piece of code, what is a better way to write it (cleaner). It is taken for granted that data will not be null, nor its length will be 0, so this check is skipped. private byte[] process(byte[] bytes) { int from = 0; if (bytes[0] == '\n') { from = 1; } else if (bytes[0] == '\r' && bytes[1]...
I'm learning Golang and have been trying to get 100% on the following Hackerrank practice challenge: Climbing the Leaderboard The code passes ~8 of 11 tests. The Hackerrank tests are time-bound and my code is not efficient enough to past the most intensive tests. I'm removing duplicates from the scores using a map. The...
I combined the ideas from this answer and a comment to this question to create a new instance of a type extracted from a type list. The index of the desired type within the type list is provided at run time, only. #include <iostream> #include <memory> class Base { public: virtual void foo() = 0; }; class A : publ...
This is my code: n = int(raw_input()) seq = raw_input().split() def minimize_list(lst): new_lst = [] k = len(lst) for i in range(k-1): new_lst.append(lst[i+1]-lst[i]) return new_lst for i in range(len(seq)): seq[i] = int(seq[i]) final_list = [] for num in seq: final_list.append(num) whil...
Ongoing development of game. The player is controlled by mouse click to move upward. The goal is to avoid meteors for as long as possible. I would be grateful if someone could critique my code. Verison 1 can be found here. Since then I have: Added intro menu screen Added game loop to contain main game logic Added he...
We have a requirement to check the size of some of our website home pages, in MB. This is to ensure that they are not growing too large, and that large images haven't been uploaded. I couldn't find much info on this, but have come up with following which is working as required. The code is designed to either run local...
I developed a Spring RESTful service that uses a JWT for authorization. To the validity of this JWT, i used two different implementations. Create a filter to intercept every request and validate request, if invalid then reject it. Create a annotation to be used in controller methods, this approach is explained below. ...
This is an implementation of the Karatsuba algorithm for multiplication: use std::cmp::max; /// Multiplies two numbers using the Karatsuba algorithm fn karatsuba(a: isize, b: isize) -> isize { // Single digit multiplication: no need for Karatsuba if a < 10 && b < 10 { a * b } else { let nr_...
I have found that my code causes my Excel to 'not respond' when it gets to this for loop, For thisRow = 2 To lastWSrow(outWS). I'm guessing this is because I am writing cell by cell and the data is too much for excel to handle. My code essentially does 55 of vlookups on sheet2. It would be similar to doing vlookup(c2&y...
I'm trying to read a file containing over 10.000 lines and each line contains an ID for an individual and a very long string composed of more than 1 million characters (numbers as example: 2200500200...205 until 1 million characters long). I need to go through this long string and retrieve a subset based on flag infor...
I am currently a student and I have an assignment in my OOP C++ course where I need to create a snake game using these specific requirements. I added some features into snake to fit these requirements Must use classes, objects, and functions Must use inheritance or polymorphism Must use vectors, arrays and or structs...
While working through some coding puzzles to brush up on Clojure, I encountered the need to use A* on some search problems. I tried to implement it from first principles/memory and that didn't go well, so I looked for existing implementations and found two (Joy of Clojure and cgrand's) but they were a little difficult...
A coding challenge on a website says to determine if an array would have an increasing sequence if one element were removed from that array. Here is the function: const almostIncreasingSequence = sequence => { const increasingSequence = arr => { for (let i = 0; i < arr.length; i++) { if (arr[i - 1] >= arr[...
I am new to C#. I just created a method where I can convert a string with the format HH:MM AM/PM to minutes. I was wondering if there is a better or more effective way to achieve the same result. static void Main(string[] args) { string time1 = "11:15 AM"; string time2 = "11:15 PM"; calcul...
This Program is a tool that allows me to import data from files that may not be easy to read just by opening; such as .db files which are wayyyyy to hard to understand just by opening the file in something like notepad and viewing the contents (this is meant for small files). from tkinter import * from tkinter import ...
This project is intended to function as a basic web server with a command-line interface for easy use. It's written in Python 3, with the help of the cmd module for the CLI itself and the _thread module (I know, I know) to run the listening/responding process without interfering with the CLI. I am wondering (with the e...
This program in essence is extremely simple, however, it can be written in many different ways. I'm a beginner at C and I've written it in 5 different variations (mostly differing in the use of getchar over scanf, while over do while loops..). Apart from readability and/or maintainability, is there any difference betw...
For my Pacman game i need to implement a pathfinding algorithm. I decide to do it with the Lee Algorithm, because in my opinion it's easier to understand than e.g. A* Star algorithm. I tried to implement it as explained on Wikipedia(https://en.wikipedia.org/wiki/Lee_algorithm) My output looks like this, O stands for Ob...
I am trying to find the year most people are alive, given a list of births and deaths. I am not sure my approach is optimal or if am calculating the time complexity correctly Break down: I sort the dates O(n log n) I walk the dates in order O(b + n log n) Hashing the births, because they pivot the shifts between the ...
One of the things I was recently investigating was the ability to generate "gauge" charts—that is, a chart which shows where a value stands within a range of values. As an example, if we know that, in general, the minimum air pressure is about 45 kPa, and the max is about 150 kPa, then we can generate a "gauge" that sh...
I have to implement a relatively basic order system in Java for part of the process of a job interview. At the moment I have working code that allows for the creation, and updating of orders for an imaginary company that manufactures bricks. Before I submit the codebase to the company I am interviewing for I want my co...
The code below is a quick, working example of a compound interest table I wrote. My concern is mainly about separating the application data/logic from the UI code. I didn't use any frameworks on purpose, just because this is an exercise. Here's the code (function() { "use strict"; function clearContents(tag) { ...
Among the mod-tools there is a few that are intended to just help get a bird's eye perspective on what happens on the site. These tools generally consist of tables. Tables over tables. Stuff that would make an executive business analyst happy. One of these tools reports some quite useful numbers as both absolute number...
My goal is to write very little code and I want a custom iterator that only changes the behavior of the dereference operator* but copies the rest of the behavior from the underlying container iterator. The following code works but is it correct? #include <iostream> #include <unordered_map> using namespace std; templa...
I have been working on a small project intended for helping beginner Python programmers getting an idea of what a real project could be like (as opposed to programming exercises and such). This application can create rudimentary user accounts and allow login with password verification. It doesn't do anything beyond th...
First time posting here, let me apologize ahead of time if this is not the correct format.. Anyway, I am new to programming and I am working on a school assignment to design a vehicle inventory system in Python (assignment details below). The code seems to be working as it should. I am questioning the 'update vehicle' ...
I have a background in Linguistics and my journey as an aspiring developer has just begun. I was hoping you could give me a feedback on the solution I have come up with for the second challenge of Project Euler, and maybe explain me why many of the other solutions I have come across were wrapped inside a single funct...
I have just started learning Python. This is code for a TicTacToe game. Can you please suggest any improvements? pos_matrix=[[' ',' ',' '],[' ',' ',' '],[' ',' ',' ']] def my_tictactoe(pos,symbol): if pos_matrix[pos[0]-1][pos[1]-1]!=' ': print('Invalid input') exit else: pos_matrix[pos[0...
I have an application using tkinter where different actions are required on mouse click, double click and when the mouse is being moved. The following class works however I wonder if there is no easier- or tkinter builtin way of doing this? from tkinter import Tk, Canvas class MouseControl: ''' Class for mouse c...
I came up with this code as a solution to a contest question. The original question can be viewed here for attribution sake: Hackerrank 2d array problem Sample input is like this: 1 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 0 0 0 0 2 4 4 0 0 0 0 2 0 0 0 0 1 2 4 0 Sample output is like this: 19 My actual code input from the submi...
I'm writing a command line app in node.js. At this stage, the app does the following: Get the version from package.json Update the package.json with a new version depending on the command line argument Commit the changes Tag the commit Push commits and tags to the remote Some comments: I'm really new to async/await ...
I've written a small script, which calculates hours since the birth. I ask use about how old they are in years, months and day. I show them approximately how many hours they have lived. Below is the code. Please tell me how can I improve it, in terms of algorithms, time/date calculation, UX, and python best practices. ...
I'm currently creating my own microframework for learning purpose and I want to make it more powerful by providing a way to register classes and instantiate them (once) only when needed. So here is my try : <?php namespace Framework\Core; use Exception; use ReflectionClass; /** * Class Container * * @package App...
Using Python 3.7.0, I've programmed a 'Game of Life' simulator. The output is displayed using tkinter. It's not meant to be limited to just Game of Life, though, as it's meant to also be used for a simple physics simulation project. import tkinter as tk #import pdb class Cell: #ref_dict allows the coords to act a...
I am getting a TLE on my submission to AGGRCOW - Aggressive cows on SPOJ: Farmer John has built a new long barn, with N (2 <= N <= 100,000) stalls. The stalls are located along a straight line at positions x1,...,xN (0 <= xi <= 1,000,000,000). His C (2 <= C <= N) cows don't like this barn layout and become aggre...
So I programmed 2048 in python3 and a simple solver, which will just target a high numbers on the board (not the best tactic, I know), but I have the problem, that this move calculation is painfully slow. Any ideas on how to speed this up are appreciated. (The logic should be fine) from enum import Enum from typing imp...
I am doing a college assignment where I have to count the number of inversions in an array/list. An inversion is defined as a tuple where i<j and a[i]>a[j]. For example in this array val arr = Array(3, 1, 2, 4) The inversions are (3,1), (3,2). So total count of inversions is 2. I wrote a divide and conquer algorithm t...
After receiving advice from my last question, I reworked the design of my program to be more generic, expandable and easier to use. This is the excerpt of the requirements: Step 1: Basic Title Case For each word in a sentence, make all of its letters lower case, except the first one that would be in upper case. The...
I am looking for some feedback on the code below, mainly for efficiency or mechanism correctness (like eval vs. subprocess). I am also curious if .find() is the best mechanism to use here. I am not familiar with regex, so my crutch (or benefit, depending) is using .find() over learning a sublanguage like regex. import ...
https://github.com/pixlark/vars-parser #![allow(unused_variables)] #![allow(dead_code)] #![allow(non_camel_case_types)] #[cfg(test)] mod vars_parser { use std::str::Chars; use std::iter::Peekable; use std::collections::HashMap; /// Useful wrapper for Peekable<Chars> which returns an EOF char /// w...
I have made a contract renewal system in Symfony and Doctrine, and it works, but I think it can be improved, but I make too many requests to the database. These are my models: Contract ------------ id reference .... ContractRenewal class ContractRenewal { /** * @ORM\Id() * @ORM\GeneratedValue() * @O...
I use the numpy.random.choice method to draw a sample from a list. The entries in the list are short dicts and look like {'name': 'SomeName', 'strength': 0.75}, {'name': 'SomeName', 'strength': 0.25}, ... I want to use the 'strength' value (between 0 and 1) as a probability indicator. To use drawResults = choice(data...
This code is a multi-threading recursive backtracking DFS algorithm to find all solutions to the N-Queens problem. The board size is indicated by BOARD_SIZE. CORES dictate how many concurrent threads to use. I've seen other Java code utilising the same DFS algorithm but getting far faster results (< 1 sec for N = 15 wh...
Within my game there are many entities, where each entity has a path (Array<Vector2>) assigned to it. No path to follow (indicating that the entity should move at all) is indicated by an empty path (the path is never null). updateMoveAttributes is called every frame for every entity, so it is important that it is effic...
I have implemented a primitive ArrayList class in C++ as part of an attempt to learn about data structures and their optimizations. It currently has: Constructor/destructor Overloaded [] operator bool insert() bool remove() short LinearSearch() short BinarySearch() insert and remove return a bool indicating success o...
I did huge review of linkedlist implementations and all of them include separate new call fornode part for entry, which has *next and T* entry values. As a person with strong C knowledge, I know what memory fragmentation means and I want to avoid too many dynamic allocations using new keyword. Application will be for e...
I am a mathematician attempting to become proficient with C++. At the moment I am learning about data structures. I am now writing a binary tree data structure using linked list from scratch. This data structure was a bit more difficult for me so my code may not be as good as the others I have posted here. I have teste...
I wrote this code for printing all sets of a String. It also prints the empty subset. Is this the right approach public class AllSubSet { public static void allSet(String s, String t) { System.out.print(t + " "); if (s.length() > 0) { for (int i = 0; i < s.length(); i++) { ...
I have 3 tables such as books, tags, book_tags. my objective is to insert books info along with tags (tags can be multiple or single). I have two methods one is insert books info 1st and then add tags for that last added book. my code is working but I'm not sure this is the best way to do it public function addTag($tag...
I have previously reviewed code that computes standard deviation using the mathematical formula E(x²) - E(x)², and warned against the use of this formula because floating-point precision is severely compromised by subtracting almost-equal numbers. I've started with the methods described in Incremental calculation of w...
Just for fun, I tried creating a function that takes the value entered in a textbox, and determines the type of it. Below is the full code. public string GetType(string inputValue) { //Variables for the parse result //Can be discarded. Used because parse function mandates output variable in...
I want a general criticism on this code. Using external modules is not an option, I can only use what comes with CPython. from collections import Counter from typing import Sequence, NamedTuple Coordinates = Sequence[float] class KNNPoint(NamedTuple): coords: Coordinates classif: str def predict(target: Coor...
The Function "Persistence Rate" is also sometimes referred to as "retention rate". It is the number of ID's in a given term/period that are also found in the next term/period. (e.g., I have 10 customers in October but only 3 of those customers return in November. My persistence rate is then 30%.) I have written a funct...
This is my attempt for C# navigation with arrow keys. Basically, when the arrow down/up key is pressed, the specified option is highlighted (so it's like a WPF/WinForms ComboBox). However, I think it looks a bit ugly, and I think many things can be made better. I put some comments into the code, to understand better wh...
A lot of the code I show here is simply setting the environment and doesn't really affect the algorithm itself, so please don't get scared away by the amount of code. The algorithm itself is showed at the bottom. If you don't want to go through all of the code, feel free to mainly look at the A* algorithm itself and on...
Background I added a few items to a codepen that displayed a list of beers. One of them was the citation of the brewer who gave tips. Previously the tips were just generated into a <p> but now I have wrapped it inside a blockquote Code <blockquote> <p> <span class="bright">Tips from the brewer:</span> "{{ be...
I'm trying to get better as a programmer and would love any feedback on my code. Especially the section in the while loop. How could I make this more readable? What would your opinion as an interviewer be of my code? I utilized python 2.7. Challenge: Given a Roman Numeral, convert it to an integer. Example: Input: "...
I'm trying to implement a deque data structure with an iterator in Java using array. Please help to review and point out things that I can improve on. public class Deque<Item> implements Iterable<Item> { private Item[] a; // the array. private int itemCount; // number of objects the array holds at any given point...
This is a toy project and I am a beginner in Python. I need to create 10 random 3-letter strings, where characters are a - z. This is my implementation: import random def random_char(): return random.randint(97, 122) three_letter_words = [] for i in range(0, 10): three_letter_words.append(chr(random_char()) ...
I wrote a finite automata implementation in C years ago. C's access to mutable, unsafe, raw pointers made it quite simple for me to link/relink the states of a finite automata. I read the official Rust Book and wanted to rewrite it in Rust. I ran into problems with recursive references (individual state nodes acting as...
I have an Angular service consisting of three methods: This method makes a call to my server to get a URL private itemUrl = "http://fooserver/api/get/item/details"; getItemDetailsUrl(productId): Observable<any> { return this.http .get(this.itemUrl, { params: { productId: productId } })...
A company I interviewed for sent me a coding problem to solve. The problem was to find a solution to a maze, not necessarily the shortest one. The input would be like so: ###_### #_____# #_##_## #_##__# #_##### The output would be: ###a### #dcb__# #e##_## #f##__# #g##### Walls are represented by '#' and empty...
I have an import books function to insert more than 5000 rows at once, I did some research and did this one but some other places I saw a different kind of methods to insert without looping and execute this. is my code got any trouble with the performance of app public function importBooks($data, $no_of_rows) { try...
I am new to javaScript, I just coded a method where I can convert a minute to a time in hh:mm AP/PM. I was then displaying the time in a table. I was wondering if there is a better approach to this? Because my code seems quite messy, with many if and else statement. function convertMinsToHrsMin(minutes) { ...
I've never used a global variable in one of my programs(of which there are few) before, is this a fair use of one? Currently, I have several classes calling a function to grab the data they require from a .yaml file stored in the user home folder. Each class constructs the full path of where the .yaml file should be us...
I have a method to query different users according to type and return userId. But there are too many switch-cases. Can someone give me some advice? private Optional<Integer> getId(int type, String appId, String openId) { Integer id = null; switch (type) { case 1: Type1User type1User = user...
The following method works fine but it is rather verbose: private function performComparison($element, $operator, $value_allowed, $value_entered) { switch($operator): case '>': $result = ($value_entered > $value_allowed) ? true : false; break; case '>=': $result ...
For executing a Process I've created an separate class which binds the possibilities together, for example reading output, start as Admin, catch Exceptions and also start all this asynchronous. Are there any suggestions to improve it further? public class ExternalProcess { public string FileName { get; set; } p...
I have written this code for practice. Here we will enter the number by which we want to shift alphabets. For eg. Enter by how many numbers you want to shift alphabets: 4 Enter string: Programmer C++ Encrypted String: Lnkcnwiian Y++ Decryted String: Programmer C++ Review this code and suggest better C++11 and C++14 a...
I have a parser that goes through two different logs, both .csv files, and checks for certain lines based off the regex code that I have chosen. This parser works fine, it just takes about a minute to parse through about 100 files. This parser is based off another parser I have that only parses through one log type and...
Here is my code: https://gist.github.com/Salil03/5fb4d512b97324c89e2580f94725a7fd The instructions are printed out from the python file. They are given here for convienience You start by typing in a letter The computer then types another letter and the cycle repeats Example: You type: z Computer types: a You know tha...
We're wanting to read data in from a config file and provide it to other python modules in a helpful way. We have found a number of ways to accomplish this that range from the module being easy to understand but verbose to use, to the module being a little more complicated but really nice to use. Below I will present t...
There are 30 checkboxes that need to have their caption compared to a cell value. The basic code is repeated 30 times for 30 different check boxes The only Lines that Change per CheckBox are the Following: The First Line - CheckBox3.Value (will increase by 1 for every checkbox) Fourth Line from Bottom - Cells(eRow, 24...
I have created a simple Employee program and I am looking for a code review. I want to make sure my use of concepts such as double-underscore methods and @property annotations are correct. I am also looking for feedback on my methodology. Please feel free to be critical of each aspect of the program: import time; #H...
I am new to web development and am working on a portfolio piece, so I would like to make sure I'm not creating obvious vulnerabilities. I am wondering whether there are any clear flaws in the following account creation and login code. Also, the relevant query wrapper is included as the last code snippet, and I am wonde...
I'm using Swift 4.0 and I'm using UserDefaults in my project for storing Strings like login or something. I have a class: class Cache: UserDefaultsManager { static var currentProfileID: Int? { get { return value(forKey: Constants.Cache.CurrentProfileID) as? Int } set { ...
For my first attempt at Scala I decided to solve a simple exercise on codingame.com. Based on a string input containing the user location, the defibrillators count and a list of defibrillators entries (id, name, address, phone number, longitude, latitude), I have to print the closest defibrillator from the user. The di...
PROBLEM The Facebook campus has N different attractions, numbered from 1 to N in decreasing order of popularity. The name of the ith attraction is Ai, a unique, non-empty string consisting of at most 20 characters. Each character is either a lowercase letter ("a".."z"), uppercase letter ("A".."Z"), or digit ("...
Problem This code is meant to solve the problem in this software engineering question. To summarize the issue: given a set of strings that are sort of similar, but not similar enough to use regex upon, how would one get out a set of those "similar strings" amongst the "nonsimilar" strings? This is apparently called fuz...
Given any four-digit number that consists of at least two different digits, if you form a number by arranging its digits in descending order, and subtract the number formed by arranging its digits in ascending order, and repeat, you should eventually arrive at 6174, Kaprekar's Constant. How can I make improvements to m...
Below is a piece of code that is responsible for serializing files. ZL_LIST and PERS_LIST are XML file structs, I have not shown them here to save space. Please check my code. package parser import ( "encoding/xml" "fmt" "golang.org/x/text/encoding/charmap" "io" "io/ioutil" "os" "path/filep...
I have written two functions- first one is to read files from SFTP and second one is to read files from Dropbox. Both functions have some similar line of code like validating extension and reading/saving file that can be extracted into a separated function and thus need your suggestion how to do it. PFB my both functio...
Recently I've been reading about classes in JavaScript and decided to code this simple form to test them out. Even if the code works I am still pretty sure I lack understanding of classes and other js utilities, for example: did I need to use constructor in this class? if not when should I use it? is there a more eff...
I have a long script here that does the following for me: I have 9000 XML files, from which I parse information, and then in about 7000 TXT files find the information out, and in the end it all save as JSON. Well, aside from what he does, he does it very slowly. Since I am very new to Python, I did not learn Python fro...