instruction
stringlengths
71
95.1k
I have written BST in Java for practice. How can I write better unit test cases. I am sure the way I have written them is not proper. Code for BST package com.r.basics.tree; import org.junit.Before; import org.junit.Test; public class BinarySearchTreeTest{ private BinarySearchTree<Integer> binarySearchTreeSUT; @B...
def draw_board(board): display_board = '' for number in list(range(len(board))): if (number + 1) % 3 == 0: if number < 6: display_board += ' ' + str(board[number]) + ' \n—————————————————\n' else: display_board += ' ' + str(board[number]) + ' ...
I've designed a database schema to store multiple translations with the objective of it being easy to retrieve data and add more translations if ever needed in the future without needing to make any change at all. Here's a dbdiagram.io of the part of the database that's relevant to this post. One of my bot commands ta...
It's an exercise from a Swift-course I'm currently taking. You are given an array of integers. Make an additional array named computedNumbers. computedNumbers should multiply each element in the numbers array by the next following element. The last element shall be multiplied by the first element. Example: If n...
I think the part to get shortest path from the cost table got pretty messy. Also can use some tips on how to avoid the extra O(V+E) work checking all edges from source to dest after getting the cost table, or have a better optimized implementation in general. DirectedGraph.scala case class Vertex(id: String) case class...
In the following hunchentoot easy-handler definition: (define-easy-handler (new-game :uri "/new-game") () (standard-page (:title "Add a new game" :script (ps (defvar add-form nil) (defun validate-game-name (evt) ...
I am trying to remove all occurrences of the words I collect in the list exclude from every text note. This is my approach. import operator,re exclude=[] for i in range(len(freq_select)): if freq_select[i][1]<=25: exclude.append(freq_select[i][0]) def remove_nonfrequent(note): print(remove_nonfrequent.i) ...
The fact is that I wanted to apply the builder pattern. But this could not be achieved, since I could not create an instance of the class with an empty constructor - this is dangerous. The goal is to make the parameter list a little shorter and more meaningful. As a result, I created a new class, the builder, which set...
I'm new to the C programming language and I just made a basic version of Python's split() function using C. Note: A major functionality I chose not to implement is the usage of optional delimiters. Official documentation of split() can be found here. #include <stdlib.h> #define TRUE 1 #define FALSE 0 #define DEFAULT_BU...
My React application manages some entities. I'm using Redux (with redux-thunk) to manage the application state. I've created a RESTClient based on Axios: export class RESTClient<E extends { id: number }> extends Client { protected path: string; public constructor(path: string, token?: string) { super(token); ...
I was recently going through some OpenCV code that finds the center of mass in a contour and realized there is potential room for optimisation. What I noticed looking back through my code is when I calculate the mass I'm using contours.size() which makes me believe that I'm calculating the moments and center of mass fo...
I am attempting to train many classifiers to test their performance with classifying tweets as being from a political bot, or not (a binary 0 or 1 classifier). My data is being read in via a csv file, with 200,000 rows, that looks like this: username,tweet,following,followers,is_retweet,is_bot AUSTINLOVESBEER,NHS fails...
I have a function that checks if a user can perform an operation based on access to a specific URL. The function parameters are the requested URL: url, and user level: lv. The conf object has stored access levels for comparison with the users access level. function isAuthenticated(url, lv){ let conf = config.getCo...
I am using the below code to retrieve nodes and values. It is taking 20 mins to retrieve the nodes and values of HKLM. I'm expecting to reduce the retrieving time Getting nodes Private Function f_GetSubkeys(ByVal WindowsRegistryKey As RegistryKey) As Integer For Each subkeyName As String In WindowsReg...
I've made a controller for Python's Turtle. The controller essentially defines an 'instruction set' so that commands can be recorded in a text file and then executed sequentially by the turtle. It acts similarly to (underlying) assembly code in that it executes these instructions in order and can also do simple iterati...
My goal is to implement a function that accepts a Follower object that will be used to report progress through a complex function (a depth-first traversal of a graph). Here's my attempt: pub trait Follower<'a, N> { fn root(&mut self, node: &'a N); } pub fn depth_first<'a, N>( node: &'a N, follower: &mut dyn Fo...
I have requirement to check list of environment variable in Linux. Based on environment variable, exit code will be different. how to optimize the below code? def check_mandatory_envs(): if "ENVCONTEST_1" not in os.environ: exit(125) if "ENVCONTEST_2" not in os.environ: exit(126) if "ENVVIRT...
This is the first time for me to ask a question in this site. Recently, I was learning python 3.x and I got a question... Which is faster ? if n==0 or n==1: or if n*(n-1)==0: Similarly, for a,b,c,d are numbers, which is faster? if n==a or n==b or n==c or n==d: or if (n-a)*(n-b)*(n-c)*(n-d)==0: I have been confused ...
I'm trying to build an iterator (enumerator) that can select specific elements in an Expression tree by traversing the tree and deferring further iteration until needed. My following implementation intends to keep it simple by leveraging the ExpressionVisitor. But since a visitor-pattern uses recursive stack calls to ...
Here I created a typed version of lodash flow that offers more specific typing. I'm curious if this exists in any other library, which optimized in tying any way — offering mainly it up to the world as a better version of flow. The return value is set to the return in the last passed function The input value is set t...
Question: A binary string is given with only 0's and 1's. A number n is also given as the length of a sub string to be considered. It is to find the number of unique substrings. Here, n=3. My algorithm: The ways I followed: (i) First, I extracted out the sub string of length 3 and converted it into a number. (ii) Then...
I've made a small script to compile Go code with Python. The result is not something I'm happy with, because: It seems overly complicated I'm worried the nested if-else with f string are unreadable Am I using the subprocess module the correct way? Any review is welcome. #!/usr/bin/env python3 import argparse import ...
I'm trying to write a JavaScript BitTorrent client in Node.js to get more familiar with the language and ecosystem. I don't know how often people use classes in JavaScript since I feel like the overall approach is to try to hide the least state possible and embrace some of the functional programming styles with callbac...
I would like to get a review of something, I have a function that creates an array of objects for a Drop-Down component (react-select). The function gets data, valueKey, labelKey and otherInfo from an object, and creates the array of objects based on the valueKey and the labelKey. const createOptions = ({data, valueK...
I have a binding model where at least one of two fields must be specified. I can't just set them both as [Required]. Here is what I came up with: using System; using System.ComponentModel.DataAnnotations; namespace MyApp.Utils.DataAnnotations { [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] pub...
This is really a simple affair, I just wonder if there is a better way to do it: let el = document.querySelectorAll('#comic img'); let loadPromise = new Promise(function(resolve, reject) { let ticker = setInterval(() => { if (el[0].complete) { clearInterval(ticker); resolve(); ...
Below I created a use function that wraps a promise or non-promise, providing the a value callback all-while preserving the original function type. type ThenArg<T> = T extends Promise<infer U> ? U : T type Func = (...args: any[]) => any type RelatedThen<PP, V> = PP extends Promise<infer U> ? Promise<V> : V function ...
I have recently started studying JavaScript, nodeJS, and reactJS on the front-end, and I have some questions about best practices to apply in this JavaScript world. I would like to ask for opinions regarding how I could improve my code. Starting with an example: I have 2 functions, with different ways of handling promi...
Here is the Egg Holder function for \$m\$ dimensions: $$\displaystyle f(x)=\sum_{i=1}^{m-1}\left[-(x_{i+1}+47)\sin\sqrt{|x_{i+1}+x_i /2 + 47|} -x_i \sin\sqrt{|x_i - (x_{i+1}+47)|}\right]$$ I am trying to find the global minimum of this function using hill climbing. Here's how the algorithm works: initialize best fitnes...
I quickly wrote this program to transform quadratic expressions in general form into vertex form. \$ax^2 + bx + c \;=\; a(x-h)^2 + k,\quad\text{where}\quad h = -\frac{b}{2a} \quad\text{and}\quad k = c - ah^2 = c - \frac{b^2}{4a}.\$ The actual conversion is easy, but with writing a lexer/parser came pain points: I tok...
Current State: I have two CSV files, their sample attached below: FileOutputWithoutBuffer-Metrics.csv File Length , Non-Buffered Time Taken (ns) 1000 , 5499114 2000 , 10971957 3000 , 15736008 4000 , 18970057 5000 , 22173215 6000 , 24612263 7000 , 26118520 8000 , 29934220 9000 , 31919477 10000 , 34940645 FileOutputWit...
Problem Definition Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. $$\begin{array}{c|ccccccc|} Symbol & Value \\ \hline I & 1 \\ V & 5 \\ X & 10 \\ L & 50 \\ C & 100 \\ D & 500 \\ M & 1000 \\ \end{array}$$ For example, two is written as II in Roman ...
Is it possible to improve this code in terms of efficiency / line number ? (avoid nested code ...). It comes from a test I failed. I don't know how I could have done it better. from collections import Counter def parse_molecule(molecule): array = [[]] for token in map(str, molecule): if token.isalpha...
Below is a python script that generates the sequence ['a', 'b' .. 'z', 'aa', 'ab' .. 'az', 'ba', 'bb' .. 'zz', 'aaa', 'aab', ..] This is essentially counting in base 27, replacing every digit with the n-th letter of the alphabet, but skipping any number that would have a '0'. import string def gen_labels(): i = 0...
I was doing following question on leetcode: String to Integer (atoi) Question: Implement atoi which converts a string to an integer. The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initi...
I've got some working code to compute the Hough transform for circles: #include <stdio.h> #include <opencv/cv.hpp> #include <math.h> #include <string> #include <iostream> int *** allocate3DArray(int y, int x, int r) { int ***array = (int***)malloc(sizeof(int**)*y); for (int i = 0; i < y; i++) { arra...
I'm trying to solve P1243E in an efficient manner. The problem in simple words is: Given \$k\$ boxes, \$i\$-th box with \$n_i\$ numbers. All numbers are distinct. We need to select one number from each box and after permuting them in such a way that after putting exactly one number back in one box will lead to all box...
This actually works nicely (we have > 2k repos) but I would really like it to start producing results right away as soon as it has any. Mostly so it seems faster than it is (by being more responsive). bbrepos(){ #clone[1] is ssh using a filter made the escaping really ugly. #If it becomes necessary ...
Today I found myself in need of programmatically getting a recursive list of the files on a remote FTP server to look for some data archives. Much to my surprise, I could not find this functionality implemented in some kind of Python library. So I decided to write a simple recursive version of ftplib.mlsd, that can be ...
I have the following function to save points cloud in PLOT3D format: def write(filename, mesh): """ Write the mesh to filename in PLOT3D format. filename: is the name of the output file. mesh: is a numpy array of size (N,2) or (N, 3) where N is the number of points. mesh[i] is a numpy array coordinates ...
basically I'm learning Java Swing by myself and I'm wondering what is the correct way to wrote code for it? I don't want to have a big class with everything in it and I want to do in the most "correct" way. For example, I have this program right there that it is supposed to paint N rectangles, where N is given in input...
A month ago I reviewed the code in Resizable split DIVs Vue.js, suggesting that the OP use computed properties and bound styles to simplify the code (at least reducing the need to use $refs to access DOM elements). Below are two variations I devised. They are very similar. The main difference is that the second uses -1...
This is the first time I‘ve used Rust, and I'd like to have some feedback on this project. The Grid class should be able to store objects of any type; it's a simple 2D grid that implements the bare minimum of interfaces. Only the copy_sub_grid function is a bit fancy here, nothing else is too crazy. pub type Coordinate...
Link to my previous question. I've implemented the other features of the board game, and made a simple learning method that stores state values and makes optimal moves based on that. I've used some OOP concepts, but I'm not sure if I've used them appropriately. Edit: I'm mainly interested in a review of the system des...
I am trying to automate this portion of code in python (code shown for 2 polygons, I am trying to do the same for 10 000 polygons). Any ideas on how to implement this using for loop or whichever fastest way you recommend. ### Polygon 1 def checkPolygon1(row): point = Point((row['X']), (row['Y'])) return polygo...
The 'friendly form' of a number is written as a sum of reciprocals of distinct positive integers. eg. $$\frac{4}{5} = \frac{1}{2} + \frac{1}{4} +\frac{1}{20}$$ I have written a python program that calculates the friendly form of an inputted fraction. import math from fractions import Fraction def decompose(x): if ...
I made this Scrabble with care since it will be mainly used by family that will not understand the error codes so that is why I catch basically every possible error, to make it user friendly. I have revised this based on an earlier post and hope to improve its efficiency even more now that I have basically redone the ...
I have some questions about best practices to apply in JavaScript. I would like to ask about my code and how I could improve. Starting with an example, I have 2 functions with different ways of handling promises Here I have a route to add a user: addUsers(req,res,next) { try { const {name,email,login} = re...
I created this morse code encoder and decoder. class DecodeError(BaseException): __module__ = Exception.__module__ class EncodeError(BaseException): __module__ = Exception.__module__ code_letter = { '.-': 'A', '-...': 'B', '-.-.': 'C', '-..': 'D', '.': 'E', '..-.': 'F', '--.': 'G', '....': 'H', '..':...
The code works not only as a normal run length encoder and decoder, but it also works for values like 3ABC (Prints ABCABCABC), but the same doesn't happen for encoding class DecodeError(BaseException): __module__ = Exception.__module__ class EncodeError(BaseException): __module__ = Exception.__module__ def ru...
I took this as a challenge and implemented linked list data structure in python class Node: def __init__(self, data, nxt=None): self.data = data self.next = nxt class LinkedList: def __init__(self, arr=None): if arr in [None, []]: self.head = None else: s...
I'm new to JavaScript and came across classes in ES6. Though they are great, I don't want to learn something that can be done in other ways. So, I created this code that does somehow similar job to what classes in JS do. Please give me feedback on whether classes does more than what I think they can do and whether my c...
Part 1: Tic-Tac-Toe with changeable board size (Part 1) I just revisited all my previous questions and saw that I hadn't updated my Tic-Tac-Toe code. So, I improvised my code as per @Austin Hastings suggestions Here's the updated code: import os from random import randint from textwrap import dedent cls = lambda: os.s...
I have an Excel file and each row within the sheet represents an employee's data. I am trying to find a cleaner way to map each row to a model object: public IList<Employee> ReadEmployees(byte[] file, string companyId) { var employees = new List<Employee>(); using (var stream = new MemoryStream(file)) { ...
I use the following code to filter data from SQL and it works fine. However, below code is vulnerable to SQL injection, but all the $post values are checkbox value (it's not user input). So can I use below code? Or do I need to use "prepared statement" as per this answer? I can only send number in array. Conn.php ...
I am studying socket.io and ended up making a connection using react as front end js and how to back end node js I was successful but I have a question as to how I made my code I don't know if it's "safe" or if I could improve on something in my back end i have this on my app.js: Here I call my router and pass my io /...
I wanted to write a C function C99/POSIX compliant that read an integer from the user input. I wanted this function to be safe and robust but I feel it is way too complex for such simple task. I am wondering whether this code is optimal. #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> ...
I have written a solution to the blood-type matching problem, as described at https://projectlovelace.net/problems/blood-types/. The problem is to determine whether a given recipient (in this case, argv[1]) will find a match for a blood transfusion in an array of available donors (argv + 2). Input blood type: B+ Inpu...
I'm trying to create a separate package in a monorepo to handle TypeORM functions. So if I have two APIs (User API, Admin API), both can refer to the same package to talk to the database. I have written a class which takes all the TypeORM entities, create a connection and export them. Please let me know whether I can f...
database relations can be found here http://www.tpc.org/tpc_documents_current_versions/pdf/tpc-h_v2.18.0.pdf SELECT l_orderkey, sum(l_extendedpriced * (1 - l_discount)) as revenue, o_orderdate, o_shippriority FROM customer, orders, lineitem WHERE c_mktsegment = 'BUILDING' -- '[SEGMENT]' and c_custkey = o_custkey ...
I'm building a simple Django app for reviews of different objects (restaurants, car services, car wash etc). I started with the app, but soon I faced first problem. Every object has features (but every type of object has different features). For example: Restaurants have garden, playground, seats, type of kitchen, etc....
I'm reasonably new to D3, and I've put together a class based React component which outputs a genomic alignment visually. The result looks like this: The component is as follows: import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import * as d3 from 'd3'; const Sty...
I have the following code which works perfectly fine. I am using the dial pad to set the number and also to send the DTMF tones. But I find the code to bit more repitive. Is there any better way to optimize the code or the approach I have is good enough ? Thank you in advance for your valuable suggestions. Cheers :) pu...
NOTES=[] hadm=[] for i in sorted(list(notes_df.SUBJECT_ID.unique())): #print(i) NOTES.append(list(notes_df[notes_df.SUBJECT_ID == i].TEXT)) hadm.append(list(notes_df[notes_df.SUBJECT_ID == i].HADM_ID.astype(float))) notes_1_df = pd.DataFrame(list(zip(sorted(list(notes_df.SUBJECT_ID.unique())),hadm,[item for...
I have a Singleton manager class for managing request model and its attributes. My main aim is update object observers when some of the object attributes changes. class FlightSearchManager { private val _flightSearchRequestModelLiveData : MutableLiveData<FlightSearchRequestModel> = MutableLiveData() val flight...
I have written this code for crawling and scraping search results from Google. But it's super slow when I run it. What it does: read a pandas column, search values in Google and take the first result link then extract the siret number in link Ex. https://www.infogreffe.fr/entreprise-societe/380760702-entreprise-de-dec...
I have different set of objects where I have to show Name UI and Menu UI using OnMouseDown and on OnMouseEnter Events. Remember Both are optional, the one object may contain(attach) both option(script) or maybe one option(script). Currently I have manage to write two separate scripts like this, that include input + act...
The end goal of my program is to use a non-linear solver to fit a set of parameters to my data set. I pull the data set from a database into a list sprays, then instantiate a list of Strip objects which parse that data for further processing. strips = [Strip(spray) for spray in sprays] Spray.cool(hw, ha, coef, units) ...
I am working on a blog application with Codeigniter 3.1.8 and AngularJS v1.7.8. The Dashboard of the application is "pure" Codeigniter, with Models, Controllers, and views, while the fronted is made up of JSONs managed and displayed by AngularJS. I operated this clear separation between back-end and front-end in order ...
I have working code for this project, but I am now in need of some help to create a dynamic ordered list within Outlook from Excel. I am trying to format comments that a user will enter into a UserForm in Excel and pass those comments into an ordered list via a collection; the issue I run into is that the number of com...
I'm a beginner in Java, and this is the first time I have written a program from scratch without a guide explaining how and where to create classes etc. Please review my code to see whether the program has been written in a logical way. The program is a very basic FruitMachine. The user clicks on "spin", and three car...
For my programming class, we have been tasked with creating a Sudoku solver; the first step of the project was to create a program which would display the game board based on input provided by the user. import math #To be used later def board_filler(): """Creates the sudoku board from user input""" board = [...
I was just trying Project Euler problem 50. The prime 41, can be written as the sum of six consecutive primes: 41 = 2 + 3 + 5 + 7 + 11 + 13 This is the longest sum of consecutive primes that adds to a prime below one-hundred. The longest sum of consecutive primes below one-thousand that adds to a prime, contains...
I implemented this console application that generates Fibonacci and Lucas sequence numbers using boost and GMP for multiprecision. There is an iterator-like class which can do any sequence based on the recursive rule F(n) = F(n-1) + F(n-2). Then there are two functions which can compute Fibonacci and Lucas numbers give...
I'm trying to improve my interview skills so I wrote one of the typical assignments - tic-tac-toe game. The main goals are: time limit: 30 minutes - 1h use only vanilla js I'll attach source but I created PR in dedicated repo as I think it'd easier to comment for reviewers. Repo: https://github.com/makbol/tictactoe/p...
I have made my first little project using C#/WPF - a simple rock, paper, scissors game. I am happy with the functionality and look but I would love to know how a more experienced programmer would refactor the code I have to bring the size down and make it more readable. Many thanks. MainWindow.xaml <Window x:Class="Roc...
I have a java project that I'm working on and I'm trying to implement in my application role-based authentication. So for example when a user is logging and he is an admin he will have access to some extra methods then a normal user has access to. In order to do that I've mapped my database in the following way. SET S...
I have multiple onEdit app script functions in my Google Spreadsheet which work individually but I cannot work out where to put the brackets to nest them. This is my code which is a little messy and probably needs a tidy up. // Cut Employees Left from Unit Standards sheet and paste in Unit Standards - Employees Left sh...
[This is my first question to Code Review and it might be a bit too much.] I want to give users the means to draw a simple diagram in the browser, and because it is partly a self-education project about the low-level entities and relationships in the browser, I haven't used one of the bigger frameworks that might perha...
I wrote a function which takes a byte and shifts the bits around. That is, there shall be the same number of 1 bits and 0 bits in the output but the bits will be shifted in position: global _main default rel section .text _main: ; Given 1 byte, shift the positions of the bits in the form 74652103 mov bl, 0x5A...
I have a list like this: seq = [-2,3,-2,3,5,3,7,1,4,-5,1,4,-5,1,4,-5] I want to get all the sequential recurrences and where it happens, I feel the way I'm doing its too brute force and in reality I want this for several lists each with length of about 300. dic = {} for p1 in range(len(seq)): for p2 in range(p1+1,...
Preface: I am learning Rust through the Advent of Code The task is to read lines from a file, parse each as an integer, then provide a summation of all the numbers. My solution looks like this: use std::fs::File; use std::io::{self, prelude::*, BufReader}; fn main() -> io::Result<()> { let file = File::open("day01...
I have been assigned to implement the morphological dilation operation without using MATLAB's imdilate, and I came up with the following solution: % ------------------------------------------------------------------------- % -> Morphological Operations % -> Image Dilation % ---------------------------------------------...
I've already created a code in python here with almost the same logic: Tic-Tac-Toe with changeable board size (Part 1) Tic-Tac-Toe with changeable board size (Part 2) Here's the code in C++. As I'm still a beginner in C++, I don't know many of the STL functions or such. Please help me on improving the code #include <bi...
I am creating routes from an array of menuItems. I have written a recursive function, which works fine but I think the code can be improved. So, I need you guys to review my code and suggest me some changes. Here is the code: const accumulator = []; const renderRoutes = (_menuItems) => { _menuItems.forEach((menuItem)...
I am trying to make an IOS tool similar to Android's ValueAnimator... more or less This is useful for situations where you simply want a value to "animate" over time, but rather than necessarily attaching that value to some view property, it is available to use as you wish. Imagine applying it to an audio filter, for ...
I have a stream of stock prices and I want to design indicators calculation for them. Indicator can be imagined as an additional chart displayed next to the prices chart. More specifically, it is usually a function that takes current price and some prices berfore that and applies some function to the resulting array. T...
So I'm using the event emitter as some sort of an event bus(If I'm allowed to call it that). The problem I've stumbled upon is that my listeners might want different data than another listener. Since I don't want to add too much and listener specific information where things get emitted. I'm using this solution, but it...
I'm trying to develop a c++ library that provide two kind of times: UTC time(self explainitory) System time(time since the system has went on) I have looked into the chrono library in cpp and im trying to implement my library, more of the same like chrono. the implementation is very complicated for me right now. I'll...
I have made a simple Timer class used for scheduling tasks. While defining the interface, I have followed the interface of a java.util.Timer class. The class is being written by using only C++11. C++17 version is provided here timer.hpp #include <atomic> #include <chrono> #include <future> #include <utility> template<...
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? Is there a more elegant solution in C++? #include <iostream> using namespace std; int main(){ long long num = 1; int divMin = 1; int divMax = 20; int tempDivMax = divMax; while(true){ if(num %...
Code works fine. What I'm looking for is C# syntax to make the foreach loop below more elegant, compact and readable. The foreach with the multiple if's takes up too much space and looks too ugly. I'm thinking LINQ syntax maybe? (Assume all the variables are strings. The final version will have better variable naming) ...
I just tried to create a program for the N queens problem. def print_board() -> None: """ Prints the board """ length = 3 * (SIZE - 1) + SIZE + 4 print() print('-' * length) for row in board: print('| ' + ' | '.join(row) + ' |') print('-' * length) print() def isValid(row: ...
Below is a code to update a google sheet using the database values. The script is working fine but it is rather slow because of the sleep function which I have to put because of the "Quota exceeding error" below. If I remove the sleep time it would work much faster but after a certain number of rows get updated it will...
Say you have two strings: exp->aaccbb comp-> aa2bb This example will return true as there are 2 chars between aa and bb. I have written this code snippet and am wondering if there is a better way do solve this problem and if I am missing any edge cases. Also, what would be the fastest way to solve this problem with res...
I wrote this singly linked list and it worked fine,Now can anyone review my code. I want to do some more clean my delete and add function. And some abstraction. #include<stdio.h> #include<stdlib.h> typedef struct q_9 { int data; struct q_9 *link; }*node; node head=NULL; node tail=NULL; node newnode(int x); voi...
One operation of my Android project is to decrypt one file (chosen in a set of ~30 files for pagination1) of ~10 Mb each and I do this with the following: fun InputStream.cipherDecryptWithSessionPwd(password: String): String { var payloadArray: List<Byte>? = this.readBytes().toList() var salt = payloadArray?.su...
How would you review this way of implementing a std::static_cast template <typename ToType, typename FromType> ToType safe_static_cast( const FromType &from ) { assert( from <= std::numeric_limits<ToType>::max() ); assert( from >= std::numeric_limits<ToType>::min() ); return static_cast<ToType>(from); } ...
I have the following code for reading a json file into pandas dataframe and parsing the fields, but it is too slow for large files. Is there a way to make the code more efficient? def extract_text(json_train_path): with open(json_train_path, 'r') as json_file: train = {'example_id':[], ...
I'm writing a Scheme interpreter in Rust, and the first step is the parser. I've finished the lexer, and would like to see what people think of it before I go any further. #[derive(Debug, PartialEq)] enum LexToken { Num(f64), Symbol(String), String(String), LeftBracket, RightBracket, } fn lex_input...