instruction
stringlengths
71
95.1k
My neural network is buggy somewhere. However, the reason I am posting here and not Stack Overflow is because a buggy neural network can still be trained to some degree and will compile/perform better than no neural network, unlike other programs. These "bugs" can be solved by optimizations/better initialization of the...
I have written a double linked list in Scala. The list should be fixed in size and items are always added to the head. if the list reaches max size then the tail is dropped. This is my code. I want to review this for brevity and functional approach. sealed trait List { var prev : List var next : List } case ob...
I am a mathematician attempting to become proficient with C++. At the moment I am learning about data structures. I am now writing a stack data structure using linked list from scratch. I have tested my class that I wrote and everything seems to be working fine but I want to see if there are any bugs or some areas of t...
The scenario is the following: There is a list of persons and places where those persons visit. Each person is connected to a single or multiple places. See the picture below, where O[i] represents objects (persons) and P[i] places, respectively. I need to get the list of places connected by those persons. Codes: clas...
I've implemented countdown timer control with arc animation that looks like this Implementation notes: For arc visualization I've created class Arc derived from Shape (code is based on this post). I've created Countdown control (derived from UserControl). For setting timeout I've added Seconds dependency property. I...
I wrote a code for a quant finance job and they told me that, besides it worked, it was poorly written. I asked for a more detailed feedback but they did not send it to me. I paste it here with minimal info about it, so it will be difficult to connect it to the company. The scope of the code is to calculate implied vol...
I've written a script in python in combination with selenium to parse different information from a webpage and store the collected data in a csv file. The data are rightly coming through. The email portion looks weird cause I wrapped two conditions in a single line to grab all the leads (in case one missing, another wi...
I want to create page when user can use form to display filtered data in table. Form has to remember its own state, because after every refresh it shouldnt change. So after submitting form I should get: form values results from database based on what was checked in form Seems pretty easy. HistoryViewModel thats all...
I have this code that I'm putting into a library script. The aim of the code is the following: The method is to connect to a remote server and run uptime on the remote server. The uptime will be displayed on the host machine, to see for how long the server has been running. The aim in a near future, is to uptime-chec...
While trying to get better at C++ I tried my hand at making a stack implementation. This is the result: #include<iostream> template<typename T> struct Node { T data; Node *next; Node(T data, Node *next) : data(data), next(next) {} }; template<typename T> class Stack { public: Stack() : top(nul...
I have a hierarchy of parts in my database. For example, one part (call it 0010102-0112-315) is a resistor. It's used in a billion different top-level assemblies. My final goal is to get all the top level product IDs related to the low level IDs (e.g. 0010102-0112-315). My current approach is to left join the table ...
I did the following exercise: Write a C program that does the equivalent of C++ string s; cin>>s;; that is, define an input operation that reads an arbitrarily long sequence of whitespace-terminated characters into a zero terminated array of chars. I wonder if it's good code. What could be improved? #include <stdio....
This is used on an Excel order form to calculate quantities in a userform for variables based on various criteria on the worksheet. It's too much code for a single Sub, but I'm not sure how I can make it any smaller or break it up. Private Sub UserForm_Activate() Dim LastRow As Integer LastRow = ActiveSheet.Cells(Rows....
Another C exercise: Write a function that takes an array of 'ints' as its input and finds the smallest and largest elements. It should also compute the median and mean. Use a struct holding the result as the return value I found it quite awkward that there is no function to copy an array into another array, so I wrot...
I'm trying to dispatch to my reducers the current status of my request. So far I'm wondering how refined the status publishing of my thunk action. I feel like my code is very verbose and I wonder if I can reduce the line quantity of it. I inform my store that the request have reached some step by dispatching a corre...
What is it used for? This is a different script from any python script which performs DoS attacks. It's designed to practice parameters fuzzing in the requests (it's requested which parameter you have to fuzz - and after choosed, requests will be made with the selected parameter combined with a 400 random characters st...
I started practicing in web-scraping few days ago. I made this code to extract data from a wikipedia page. There are several tables that classify mountains based on their height. However there is a problem with the size of the matrices. Some of them contain 5 columns while others 4. So I made this algorithm to extract ...
I am trying to access data from Coinmarketcap API in Python and came up with the following code: def fetch_coin_prices(**kwargs): """Retrieve cryptocurrency data from CoinMarketCap and return a dictionary containing coin names with their current prices. Keyword arguments to this function are mapped to the ...
My team and I are trying to implement a secure API and would appreciate some feedback on the following: If there are areas of improvement in the current code to improve security Recommendations on other secure API implementations, if any, that would fit our requirements better (see below) If there are any major loopho...
I have a live search project and I don't know if it's secure enough or not. I don't access it directly, but I get data by JSON so I shouldn't worry about slashes or quotes, right? The PHP code: <?php if (isset($it_server)) { class search{ public function gettingvalues($search_value){ require_onc...
Exercise: Checking if a sentence is considered valid under the following conditions: Numbers less than 13 are only allowed in their written form, e.g "twelve", but "14" is considered valid. Only 1 period marker is allowed and it must be the final character First letter must be uppercase number of quotation marks in th...
I'm using 1.8.0_162 version of Java and here is my task about stream framework Map<String, BigDecimal> paymentAmountInfoMap = serviceResponse .getPayments() .stream() .collect(Collectors.groupingBy(x -> String.valueOf(x.getDueDate().getYear()))) .entrySet() .stream() .col...
After implementing suggestions from my previous question and after modifying I have written this code. Function sortAccordingArrivalTime() sorts arrivalTime burstTime and priority according to arrival time. I have tried to enter Arrival Time, Burst Time and Priority in respective order for each process at a time. Help ...
The following is code that I used to do a task. the code runs fine but takes over 2 minutes to get executed. And this is with only one rule (Rule_1), the rule is checked using an .exe ( written in CPP).Actually there are many CSV files that are needed to pass through the rules. My question is will the program always us...
I have the following command bonded to my button, It's supposed detect the current used theme and change it (Dark or Light). var existingResourceDictionary = Application.Current.Resources.MergedDictionaries .Where(rd => rd.Source != null) .SingleOrDefault(rd => Regex.Match(rd.Source.Or...
To train my Python skills I have made a vocabulary trainer which runs on a terminal: import random import os import sys FILE_PATH = "./words.txt" class Entry: def __init__(self, french, english): self.french = french self.english = english entries = [] if os.path.isfile(FILE_PATH): words = o...
As in many teams, me and my coworkers are putting ticket number into beginning of each commit message. If your branches are starting with ticket number it is easy to create prepare-commit-msg hook to automate this action, and since I'm a front-end deveoper, I decided to write it as a nodejs script. Look at what I came ...
This is my naive approach: $sample1 = [3, -20, 1, -19, -4, 6, 77, -1, 0, 6]; $sample3 = [4, 5, -7, 0, 2, 44, -3, -5, 66, -7]; $sample4 = [4, 25, 1, 6, 9, 5, 999, 4, 43, 2]; $sample2 = []; for ($i = 0; $i < mt_rand(10, 30); $i++) { $sample2[] = mt_rand(-1000, 1000); } extractNumbersThatSquaresAreGreaterThan($sample1...
I've posted the code for the following question. What could be improved? Q: Write a program that allows the user to type in a phrase and then outputs the acronym for that phrase. Note: The acronym should be all uppercase, even if the words in the phrase are not capitalized. def main(): ## input the phrase ...
I am diving into Data Analysis with pandas, and I have just written this Python script to calculate the average of hotel review scores of each country. The dataset contains an individual average score for each customer review, like: 8.86 or 7.95. My goal was to average all these individual scores for a particular count...
I have the following program that opens a Word document template using the OpenXML library and replaces a couple of phrases with their counterparts from what will be a database (right now its just dummy data). Something about the if-else struture in the nested foreach loops bothers me. Is there a better way I can acco...
Intro You've mastered the Rubik's Cube and got bored solving it, so now you are looking for a new challenge. One puzzle similar to the Rubik's Cube caught your attention. It's called a Pyraminx puzzle, and is a triangular pyramid-shaped puzzle. The parts are arranged in a pyramidal pattern on each side, while the layer...
I am studying Java. Can you criticize my code and tell me what I need to do to make it better? I have code that reads a txt file(product base). It contains tabular data where lines are formatted as: id productName price quantity We launch the code with: -u id productName price quantity - update line; or -d id - delete ...
I did this small project where there are six one-liner anonymous methods that can swap case of a given string of any length. For example "heLLo, woRLd" ==> "HEllO, WOrlD". I used this string as the example to demonstrate how each of the function works. This string "heLLo, woRLd" can simply be replaced with Console.Read...
This question is a follow up of: Calculate min, max, mean and median out of array I took all the suggestions an reworked the code. Like the description of the excercise suggests i only use one function for all the computations. Also with the sorting the max and median values can now be calculated easier. I wonder if it...
I did the following Excercise: simulate single inheritance in C. Let each "base class" contain a pointer to an array of pointers to functions (to simulate virtual functions as freestanding functions taking a pointer to a "base class" object as their first argument). Implement "derivation" by making...
I'm trying to ensure that a Sinatra hash always has a valid value. Is there a more-concise way to write this? params[:v] = if [:icons,:list].include? (params[:v] ||= :list).downcase.to_sym then (params[:v] ||= :list).downcase.to_sym else :list end
I have a form that I have broken into several different components in Angular. By the end of the form, all the data needs to be submitted together. My thought process was to create a provider to handle/save the form data and at the end of the form, use the provider to package it up so it can be sent to an API. I have ...
Description: Given a binary tree, return all root-to-leaf paths. Leetcode /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ Code: class Solution { public List<String> binaryTreePaths(Tree...
Edit: This code was reworked and repostetd under a new question: Non generic Skip List implementation in C++ Version 2 To sharpen my C++ skills I tried to implement a skip list. I was quite happy when it finally seemed to work correctly. Unfortunately, the implementation is kinda slow. When I run the main were I rando...
I'm working through the classic Cracking the Coding Interview book. I'm trying to solve the following graph problem: 4.1) Route Between Nodes: Given a directed graph, design an algorithm to find out whether there is a route between two nodes. I've written a solution in JavaScript and found it was a lot less complic...
Introduction This is a follow-up to my previous question. This code rocks new ground-up implementation of core functionality, which I made from combining @vnp’s and @JDługosz's answers. The core functionality got ~100 LOC decrease and insert gained 15-25% performance gain. It turns out that my remove tests didn't test ...
function outside(x) { function inside(y) { return x + y; } return inside; } fn_inside = outside(3); //1* - Think of it like: give me a function that adds 3 to whatever you give it result = fn_inside(5); //2* - returns 8 result1 = outside(3)(5); // returns 8 1*,2* - Since each call provides potentially diff...
Honestly, I'm doing a practice and get blocked. Problem link. The problem is simple, given a string, calculate the number of max length palindromes (Any substring is valid, which means you can take any chars you want and reorder them as you want). Return the result modulo 1000000007. For example, given amim, the answer...
I need to process some data (one of its columns contains a json/dict with params- I need to extract those params to individual columns of their own; catch- some rows have some parameters, others have others.. but all rows put together have 1142 individual parameters.) and so I've written the following script, which wor...
I have a java service class which will call a REST service and get response back. It is working fine in developer environment where less requests are made, but I still wanted to get a review. My service method call is like: private String getResponse(Object request, String cUri) { String responseStr = StringUtils.EMPTY...
This is a python (2.7.13 according to sys.version) script that reads systemd service names from a file and gets their CPU and Memory usage. It does that by first getting the main PID of the service by either searching for it in /var/run (most services have a pidfile containing the main PID there, however, there are dif...
I've written my first C++ multithreaded application (as far as I can recall) which determines if a regex can be found in a string. This code works correct to the best of my knowledge. Could you gals/guys tell me what I could improve on this code? main.cpp (one file): #include <iostream> #include <chrono> using namespac...
Thought this would be a fun thing to code, basically it is a simulation of the prisoners dilemma. I'm trying to improve my coding so any critiques about how to get better would be appreciated. Also if you have any suggestions for other strategies for the game, those would be appreciated as well. The goal is to have the...
I wrote code to search by keyword, and it will check all of the values from the object property, including an array in the object. But apparently the code is not optimized as it takes some time to execute the function, and it is subject to client PC processing power. Here is the sample of the object: { clientId: "...
I used MySQL, but it was inconvenient so I made a wrapper. It works, but I'm unsure if there are any issues. Used node module - mysql2, bluebird sqlWarpper.js 'use strict' import mysql from 'mysql2/promise' import blueBird from 'bluebird' function sqlWrapper() { this.pool = null this.connection = null thi...
I've implemented Luhn checksum in Python version 3. I want your comments and opinion about my code. I know it's embarrassing code and that it doesn't follow python best practices but it works!. The x in doubledigit parameter means that if the boolean is False, the index of the number is odd so we don't have to double i...
I wrote JS to clone image and attached this action to button. It works but I'm not sure that this better way to do it. My questions: is it correct to use querySelector to return elements, or is it better to add additional classes or id for buttons and pictures? use cloneNode is optimal or better use other ways in this...
I solved the problem posted from Make School Trees and Maze article, which asks me to searching a maze using DFS and BFS in Python. Here's the final output from PyGame: I would like to ask for code review, as I paste my code snippet below: Here's my DFS and BFS solution for solve_maze.py code review for implementatio...
I wrote this class to generate a random "image," similar to a QR code, using strings. How can I make it better (I am a beginner in programming)? import random """ N is the length of squared field to be generated""" class genImg(): def __init__(self, N): self.N = N self.field = [] def genField(self): f...
Rate my code and tell its quality like how well its formatted and all. I want to see how well its written. I have recently started learning Java. so some suggestions will also be appreciated. package e.banksolutions; import java.util.Scanner; import java.util.Random; import java.util.Date; public class EBankSolution...
I'm attempting to solve the problem "Synchronizing Lists" on Kattis.com. In a nutshell, the problem involves being given two lists: the lists are then to be sorted smallest-to-largest, correspondingly indexed elements paired together, then the second list is output, in the original order of the corresponding elements o...
I'm caching the value of a configuration object in a private field: private Configuration _config; public Congifuration Config { get { return _config = _config ?? GetConfig(); } } Config is populated by reading a JSON file from disk, so performance is an obvious concern. I like how concise this code is. But I'm wary o...
I have built this small class as a small library to be able to talk to a server that uses CapeSoft's NetTalk library as socket library, and which uses the Whole Packet Protocol, which is a simple protocol made by CapeSoft for the communication between NetTalk Apps. However, I need to talk to this "REST" Server to get s...
Here is a class which I have written to create a simple Stack data structure which can be shared across multiple threads. It's a simple LIFO which has 2 operations: one to push onto the top of the stack and the other one to pop from the top of the stack. Please help me to find any issues with it. package com.thread.te...
I am looking for "complete" producer-consumer sample using C++11 memory barrier. (I have derived following example from Jeff's article and added a line to make it complete.) void SendTestMessage(void* param) { // Copy to shared memory using non-atomic stores. g_payload.tick = clock(); g_payload.str = "Te...
I made a post that follows from this here. I made most of changes that I could understand from the following link, and here is now an update to that original post. I just want to see if there is any major changes that I need to consider making and perhaps to gain some more insight into how to achieve making those chang...
I have an autocomplete implementation in Python, and it passed all of the unit tests that I have included at the bottom. #!python import random import time def get_words(filename): with open(filename, 'r') as f: words_list = f.read().split() return words_list print(words_list) def binarysearch(...
I want to get this code reviewed for a function I wrote that pulls log messages from a MySQL table: def get_logs_messages(request_id, destination=None): """ get logs from deployment table :param int request_id: request id of selected deployment. :param str destination: destination site :return: ...
Many conditions need to be scanned for the first one that matches a set of tests. If there is a matching condition, that conditions ConfigId should be returned. I have a way to do the matching of conditions, but there are too many continue statements. Is there a better way to perform these checks? private Integer match...
I am a bit new to Python. This is my first code review, and I am excited to get a critique on how to make this (very simple) shift cipher more Pythonic, cleaner, and more organized. alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j','k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z...
I came across a problem that needs to reverse each word in a string without affecting space in it. For example, if a string has two spaces between the word, the answer needs to have space between two words. These are example test cases, I have been given /This is a sentence/ / This is a Sentence / My approach is: st...
My first (real?) program. The client connects to a Django restframework API by sending user credentials to obtain a token for headers. Then the user can drag and drop an image from a OS folder into the terminal and press enter, then write a title for it to upload. The image(s) URL is obtained from the server and then t...
Python3's async/await syntax is great, but it does create a divide between libraries which are async-based and those which are not. For example, boto3 (AWS API library) currently doesn't work with async. There is a separate project, aiobotocore, attempts to recreate some of this functionality in an async context. I hav...
I'm writing my own MVC framework for learning purposes. Usually in my projects I like to use AJAX to send requests and retrive data. Now my doubt is if this can be a best approach to make a one page dashboard. I've created an .htaccess who will display only folders that have an index file inside, the dashboard will be...
The story here is about a console application that replays to a test system string clauses already imported in the production system. Looking forward to your comments. namespace MyCompany.Department.ProjectXYZ; { using System; using System.Collections.Generic; using System.IO; using System.Linq; usi...
I've written a perl script that creates a csv file consolidated of values from multiple files. This file that I've created is then used to update certain rows in a main excel spreadsheet my company uses. I've created a VBA script that scans the main file for values that match up with those from my perl generate file an...
Program purpose The purpose for the program is to create a file containing the effective inventory for each stocked item stored in a collection of shops. Input and algorithm details For clarity, in the descriptions below, variables in the C++ program use this style: nShopID, while fields in CSV files are shown like t...
This is a follow my rock-paper-scissors program, original post here: Simple rock-paper-scissors game Looking for any feedback and recommendations on ways to keep improving. Quick notes on changes: Removed the use of using namespace std; Added inheritance structure. Added the use of enum variables to replace strings to...
My idea was to take in the function and perform a self cross product so that I could check every pair against every other pair. I'm new to Haskell so this solution is probably rough. My question is, is there a better way to emulate a nested for loop rather than a cross product? Also, is there any way to collapse my ugl...
Please provide general and any specific criticism of the following which is intended to provide a map of SF transit cars. The code can be viewed in the working version and also in a group of gists. If this isn't the appropriate place or way to request a review please let me know. Feedback received so far indicates the ...
I have written this code in C# to connect to an Oracle Database, omitting the tnsnames.ora file, then place results from a query into a CSV File. Is there more efficient way to do this? (Such as reading in the data into a DataReader rather than a DataTable) Please review and tell me what you would change. using System;...
I have the following code that causes my excel to 'not respond' however if I step through put a breakpoint at the loop For thisScen = 1 To UBound(stressScenMapping, 1) to Next thisScen and run it next by next it works but takes long. When running at once it takes so long. It slows down at this For triple loop. It does ...
I am attempting to make an eCommerce site from scratch. Right now I have the following code that gets all the items from a Firebase Firestore database and then adds HTML into an items div element based on the item's info. var items = []; var itemsDiv = document.getElementsByClassName("items")[0]; db.collection("items"...
I am implementing a program to draw a box of text next to some other drawn object (that can have any position and dimensions) and the text box should always be visible, even if the drawn object's width is of the entire screen and vice versa. They should simply not overlap. This is a code to position the text on some re...
This is a form that I want to use to enter users into a database. I used MySQLi with prepared statements. I want to make sure that I sanitized my data well. <?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the...
I have a contact form that will perform validation on the server. Right now the form checks if the fields are empty or not. My goal is to expand it following: Check the fields for particular format, if it is a proper email format, phone number format, etc Set the field as required or not My form is as below, I apprecia...
I want to substring a String from given start index and given substring length. if the string is empty then returns String.Empty if the string length is greater than start index then it substrings from given start index to given length... if the string length is less than start index then it returns from start inde...
To learn network programming in Python, I have written a small piece of code which is constituted of 2 modules, a client and a server. The server listens to a specific port provided on command line, then the client connects to the server, and send a file to it. The client sends the size of file at first, then the conte...
I have two lists of numbers: $$\{i_1, i_2, i_3,i_4\}$$ and $$\{j_1,j_2,j_3,j_4\}$$ The problem I want to solve is: Inside a loop, if the following two conditions are satisfied, then it will do something I want, otherwise it just cycle the loop. The conditions are: Both lists contain four different numbers; If ignoring...
I have a list of 2D arrays which comes from a time evolution PDE (in \$(x, y, t)\$) that I solved numerically. There are \$k\$ arrays, which all have the same dimensions, and the arrays correspond to a solution field of the PDE at times \$t = 0, 0.1, \dots, 0.1k\$. I wrote a program that takes in this list and computes...
Could I please have some ideas how to improve this conversion calculator I have made. I am currently not looking to add any more quantities, but rather trying to enhance the usability and add some quality of life changes to it. If there are any major ways I could make the program more efficient that would be helpful a...
Yesterday someone guided me through this article and I'm wondering whether I should use try-catch implementation or not? I have the following code below which is actually a RESTful service and I have implemented the try-catch pattern. I'm throwing errors only in debug mode just for testing purpose and during the releas...
This code needs to get two inputs: one is the full address of a directory and another the file extension that it will be changed. These inputs cab be added in the default section of parser.add_argument as in the example. It will overwrite the files with the new copyright: import csv import argparse import os clas...
I'm currently trying to implement the singleton pattern in C++. After reading about it for a while now, it seems like there are a really large amount of different ways to do this. Is the way I ended up doing it correct or did I miss out on something important here? Is this implementation thread safe in modern C++ (I r...
Yesterday, I very quickly, in an hour, wrote the very first version of my long-term archiving + encrypting shell script. I am aware it may have too many flaws, but none of them really prevent it from normal operation, so before I take another step and restructure it with printf and better error reporting, structure, ex...
Here I have implemented code for Round Robin CPU Scheduling Algorithm. scheduling.h header file is also used in Shortest Job First Scheduling Algorithm and Priority Scheduling Algorithm, so it contains common data members and member functions. First I have calculated end time in calcEndTime() then using formula turnAro...
I've just started with Java. The code below calculates Body Mass Index (BMI). Could someone look for my code and assess it? Maybe I should write something more? All advice will be very helpful. import java.util.Scanner; public class BMI { public static void main(String[] args) { Scanner scanner = new Sca...
For a project, I need to write a basic template manager who will be responsible to load the requested HTML or PHP template when the user clicks on a menù link. It's like a page loader since that all the loaded templates are static HTML pages. I want to improve it if is it possible. Here is the code. on the main index o...
I'm relatively new to Go, which is why I decided to post some code here. My goal is to en-/decode a TCP stream. The individual data packets length-based. The first two bytes are the unsigned size in little-endian byte order. The size includes the size field itself. The methods I wrote seem to en-/decode the packets as ...
Using Qt, I've got this code in order to protect access to some shared data between threads. I'm pretty sure the idea is correct, but I don't know if RVO and/or RAII could potentially screw the get function. I'm much more used to C and while I understand the idea, I'm not totally familiar with all the "gotchas" for the...
Here is my code: import sys import math def dist(a,b): return math.hypot((b[0]-a[0]),(b[1]-a[1])) def minimum_distance(x, y): points = list(zip(x,y)) points_y = sorted(points, key= lambda z:z[1]) points.sort(key=lambda g:g[0]) return min_dist(points,points_y) def min_dist(points,points_y): if ...
Since the previous question I posted here was not found as interesting as I expected, I decided to post a new one. I made a function solely for the purpose of having fun. That is, a function that checks if two strings are similar with a given %. int case_insensitive_chrcmp (int ch1, int ch2) { return ch1 == ch2 || ...
I've written a script in scrapy to grab different names and links from different pages of a website and write those parsed items in a csv file. When I run my script, I get the results accordingly and find a data filled in csv file. I'm using python 3.5, so when I use scrapy's built-in command to write data in a csv fil...
I just started coding programs with python. As a challenge I wanted to program something to print out the Fibonacci Numbers. It looks like I've done what I wanted to do (I checked the first few numbers) and because I just started coding, I obviously don't know if this is a legitimate code and somebody would code it lik...