instruction
stringlengths
71
95.1k
I want to display a text of variable length in a cardView. To make the text fit, I split the text after every 500 Chars and add the substring to another relativeLayout which is then added to a HorizontalScrollView. But I must define a length of the relativeLayout, otherwise it is just a long one-liner in the ScrollVi...
The following is given: CREATE TABLE City ( city_name varchar(255), country varchar(255), primary key (city_name) ); insert into City(city_name, country) values('London', 'England'); insert into City(city_name, country) values('Santiago', 'Chile'); insert into City(city_name, country) values('Edinburgh', 'Sco...
I have a navbar menu with two styles: First one is a tranparent menu. I use it when the page charges. Second one is a scroll and responsive (not yet) menu. I use jquery to transform the first menu to the second one because they have two different fully styles, but I don't know if this will affect to general page cha...
I made a cipher on python and I want to know how good it is, I calculated there are about 10^1025 possibilities for the key, is that any good? I can easily make it bigger. I mainly focused on the 'hard encoding' by the way. Here is the code: import random import itertools print (''' READ THIS BEFORE USE T...
I'm trying to find an efficient way to aggregate data for reporting. Let's say I need to aggregate the following data in 5-second intervals: CREATE TABLE RawData ( Result FLOAT, CaptureTime DATETIME ); INSERT INTO RawData VALUES (2.3, '2018-04-01 00:00:00'), (2.5, '2...
I'm looking for a code review for the following system that I created. It allows a landlord, to add a tenant to start a tenancy. It has added, accept, reject, and prohibits a tenant from adding themselves. Tenants can't add landlords. First thing up is my controller The form is what is rendered when the landlord click...
I'm learning Python for 2 months now and I'm working on a little exercise app calculating percentages. I'd like to ask for a code review and comments. I'd like to make sure I'm following the right habits from the beginning. # coding: utf-8 # In[9]: def percA(perc, num): perc_a = perc/100 * num return perc_a ...
The following code is a website with a nav-bar on it. It uses some simple JavaScript to make it work: index.html: <!DOCTYPE html> <html lang="en-US"> <head> <meta charset="UTF-8" /> <title>SigmaCubes - Home</title> <meta name="author" content="Julian Lachniet,Simon Kwilinski,Jacob Wysko" /> <meta name="descrip...
The following is my implementation of a stack using a linked list. class EmptyStackError(Exception): def __init__(self): super().__init__("Stack is empty: Invalid Operation!") class LinkedList: class _Node: def __init__(self, data, next_node=None): self.data = data self...
Intro and code I have the following function that calculates an object's "next" position and velocity (in 1 dimension) given a boundary [0, max]. public TwoVector<Double> getNextPositionAndVelocity(double position, double velocity, double max) { if (position + velocity < 0) { return TwoVector.<Double>builde...
As part of the project I am currently working on we want to log our UI component errors as well. I developed this package as a base. It's a factory (basically, not sure if it's correctly a factory). There is one function exposed configure that takes the parameters that each service (of the project) needs to supply and ...
//App.jsx import React, { Component } from 'react'; import { initialiseLogger } from './logger'; class App extends Component { constructor(props) { super(props); initialiseLogger(props.environment); } render() { return ( <Component /> ); } } export default App; This it he top level of m...
I coded an algorithm which shows prime numbers in the ranges provided by the user. The first line states the number of test cases. Example: INPUT 2 1 10 1 5 OUTPUT 2 3 5 7 2 3 5 t - number of cases, n and m is the range (t<=10) m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space And here is my prob...
Context: I had asked a related question on Stack Overflow. On receiving several helpful hints from the commentators there, I could successfully implement averaging of the size distribution over a certain number of iterations. This question is about the modified version of the code I had posted on Stack Overflow. Brief ...
The following code works and will be put into cron on a AWS server (not sure what specifications, cores, kernels etc) at a every 1 minute frequency. However, it's my first time putting a script into production, so I'd like some help reviewing this code. Please look it over and point to any hidden mistakes or something ...
This my opportunity object which is a part of my angular app.component.ts file. In my template(HTML of this component) I want to loop out different skills backgrounds nationalitiesetc. array using *ngFor*. So I've filtered out these array of objects based on a property option which can have only 2 values either preferr...
I have a homepage that shows how many questions are in a certain category which is done through tagging. The functionality is working great, it tells me how many of each there are. However, newrelic's agent is telling me that there can be anywhere from 16-24 database calls per request, which seems excessive to me. How...
I have been playing around with these two functions for a bit, dunno if this is practical though. I have only been learning C++ for a couple of days, coming from a Java background. There we had a function that does this for us; I tried making something similar. #include <iostream> #include <string> #include <vector> ...
I need to speed up my algorithm. It is about finding the height of a tower. The tower is built from buckets. Each bucket has height and radius (1 <= height,radius <= 1000). Variable bucketCount describe how many buckets are placed on tower (1 <= bucketCount <= 10^6). We set buckets in sequence. Thickness of bucket is 0...
In the question of how to reverse a string in Java, a comment mentioned that combining Unicode code points need to be taken into account. The below code works as intended for all test cases I tried. Probably there are some edge cases in other scripts and languages I do not know. I'd like to learn about these, as well a...
I've made an algorithm/ function to get a user's region based on their GPS coordinates. It primarily looks for big cites and counties for the region and the state for the outer region eg. orange county, Texas. This wasn't simple as GPS / maps isn't a perfect science. Sometimes I might only get a town and a country to w...
Today I created my first simple AJAX application. It works fine, but I am a bit unsure if I did everything correct. I'd like to use the code as template for future projects. function _solve(id) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { var DONE = 4; // readyState 4 means t...
I've started learning MonoGame and C# lately, so in order to get more confident with both and do something not completely trivial, I've built a Naughts and Crosses game. I am using 7.1 version of C# (value tuples here and there...) The game does the following: Plays Tic-Tac-Toe (AI is unbeatable) Keeps score for play...
I have some Python code which uses NumPy which computes gradient of a function and this is a big bottleneck in my application. So, my initial attempt was to try to use Cython to improve the performance. So, using online guides, I was able to port this to Cython easily but got a very moderate speedup around 15%. The fun...
The script below is used to determine relay operating times, as defined in the standard IEC 60255. The equation and relevant information can be found here. curve_equation takes three input values, and outputs a list of values representing the trip times for currents in the fixed range np.logspace(np.log10(Is), 5, 1e2)...
The "Rounding Error" problem of Round 1B of Google Code Jam 2018 is as follows: Problem To finally settle the age-old question of which programming language is the best, you are asking a total of N people to tell you their favorite language. This is an open-ended question: each person is free to name any language, and...
I've been working on a Python script which is an MP3 Tag editor. I need someone to go through my script and tell me whether I have written it correctly (following correct coding style) and where I can improve the code in term of readability, functionality, making it more Pythonic, etc. Since it is little long and I've ...
For some reason, this is the first time I've ever written an implementation of the Sieve of Eratosthenes. I basically just stared at the Wikipedia walkthrough of the algorithm until it made sense, then tried making the algorithm in idiomatic Clojure. I'm not using an boolean array representing every number. Instead, I ...
Accepts a String (or a char array) as an input and stores the data in a tree structure. For example, given the input: <foo> <bar>baz</bar> <qux fox="jump"/> </foo> Output will be: XMLElement{elementName='foo', children=[XMLElement{elementName='bar', elementValue='baz'}, XMLElement{elementN...
I'm looking for feedback on this AVL tree implementation. Particularly on the overall structure, readability and abstraction. I've tried to keep all AVL specific operations inside the balancePath method to allow for easy conversion to a red/black tree with only minor changes to the rest of the code. Are there any furth...
Requirement After a user draws two circles with their mouse successively, the program should draw all common tangents, if any, to them. Here is my implementation function InteractiveCommonTangent tolerance = 0.001; color = 'b'; style = '--'; width = 0.5; circleCount = 1; buttonDown = 0; x1 = [0 0]; y1 = [0 0]; x2 ...
The problem I am trying to solve is as follows: F. Reducing Salary time limit per test: 2 seconds memory limit per test: 256 megabytes Sohieb started working at Hogwarts School of Witchcraft and Wizardry. Ibrahim The school headmaster told him that he will get a positive integer salary equals X, then Ibrahim mad...
This challenge was pretty simple - be given the coordinates of a king and a queen on a chess board and determine if the king is in check. Input is the number of test cases with each test case on a new line, king coordinates first. I read in via text file. Output "Y" or "N" as the result for each test case. e.g. inpu...
I am working on a project where users have to log in then if it is correct it creates a cookie to process requests. I would like to find a way to auto-renew sessions every day without affecting the user or requiring the user to log in again. I would like to also know if I overlooked any security flaws such as SQL injec...
I would like feedback on this class library, mainly the architecture. It works very well. But maybe someone knows how to improve it. This is a class library for working towards an external system. I reuse this class library in multiple solutions. The scope of this review is limited to "Retrieve the customer". Since thi...
I'm a beginner yet, and currently I'm making a site about The Flash (just to practice), and yesterday I figured out this code to make my next/previous (episode) buttons work correctly. I'm glad I found a way after hours, but unfortunatelly it's pretty long. So I'm wondering if someone could offer me a shorter code for ...
I am trying to reduce my Docker image size. The folder that I am trying to dockerize is 628K in size. Checked using: du -sh foldername Below is my Docker file: # Use an official Python runtime as a parent image FROM python:3.5-slim # Set the working directory to /app WORKDIR /app # Environment variables ARG access_k...
The reason I created this is because I wanted my string values to be type safe and I wanted to decrease the amount of bad data that has crept into my system due to hard coded values in the past. There are different ways to solve this issue, like a lookup table with a key value pair but this is not a direction I can mo...
Python 3.6 and Sqlite3. I have a database with something like 300K entries, each entry has several fields (date, username, etc) and a "text" one. I have a list of 200 words and for each word i have to return the number of entry in the database with the word in the "text" field. Currently, it takes around 1 second pe...
My algorithm works but it is too slow. I have to ask for help with improving this algorithm because the website which checks this, kicks me for too slow execution. What should I improve here ? Details: Given a sequence of 2*k characters, please print every second character from the first half of the sequence. Start ...
I have written a program that makes it possible to write as cool as the cool kids. All you have to do is enter the boring, normal text, which is then transformed into an exciting, stylish text. Is there a possibilty to make the code more performant without decreasing it's readability? Example Output: I H@Ve wRITTen @ ...
We have an odoo server running (http://www.odoo.com/documentation/9.0/api_integration.html), which allows us to programmatically query and download invoice reports as PDF's We're running this on python 2.7.3. I'm looking for tips on DRYness, future maintainability and help on blind spots in the code where something mi...
I posted a C++17 version of wrapping functions for the “two-step”, on this Answer on StackOverflow. It’s more than just handy to have a wrapper, as I was searching for good solutions on how to use begin (etc.) in a constructor initializer list, so there was no scope to add the using declaration to, and I could not push...
I implemented a std::array wrapper which primarily adds various constructors, since std::array has no explicit constructors itself, but rather uses aggregate initialization. I like to have some feedback on my code which heavily depends on template meta-programming. More particularly: Are there still cases where I can...
In my first question I tried to show “real” coding concerns while still keeping the implementation brute simple; using a loop over data rather than a string of separate testing statements, isolating the algorithm from the I/O of game play, allowing easy (compile-time) modification and extension. Now, I present ame 2. A...
I create a 2dVector class to use a position coordinates in a pygame application and maybe in the future as part of a physics engine. Does this implementation has any huge downsides? Is the type hinting ok? import math import random from numbers import Real from typing import Union, Sequence, cast VectorType = Sequence...
I am trying to compare two Log lines based on some conditions, in order to sort them: Code: public static final Comparator<String> HTMLcomparator = new Comparator<String>() { @Override public int compare(String line1, String line2) { HTMLLogLine htmlLogLine1 = new HTMLLogLine(lin...
So I wrote a 2d rectangle class for use in a 2d pygame based game engine. It uses the vector class from this question, so if you want to test, you need that code too. I want to ask: Does this implementation has any huge downsides? Is the type hinting ok? Do I have any typos? from numbers import Real from typing import ...
I've been diving a bit into JavaScript for the first time in forever, generally trying things out, and getting acquainted. I gave my toy project the following requirements: single-page react app uses firebase for authentication matching server-side session with a persistent websocket connection. the connection isn't "...
Background I'm writing code for an 8-bit MCU with very limited RAM (1KiB) and program flash space (64KiB). I have a C++14 capable compiler with no standard library implementation available. This is a good enough excuse for me to do some recreational template programming. :) In the project where I intend to use this I n...
Followup to this I have created a simple HTML5/CSS3/JS website with a navbar and no content. index.html: <!DOCTYPE html> <html lang="en-US"> <head> <meta charset="UTF-8" /> <title>SigmaCubes - Home</title> <meta name="author" content="Julian Lachniet,Simon Kwilinski,Jacob Wysko" /> <meta name="description" co...
Purpose I've never implemented a DoublyLinkedList and thought it would be a good data structure exercise. I tried using outside resources as little as possible. I also tried to keep things as simple as possible Discussion The DoublyLinkedList is made up of a Node head, a Node tail, and an int length. I did not generici...
Please go through below code and improve the quality by reducing the IF conditions: I have 2 jsons, first one is the source and second one is the updated json. I have to compare both values and set true/false flags. Based on the flags i need to proceed further. I am checking below conditions: NULL changed to DECLINED...
I have recently implemented this utility class for going through an instance's member fields recursively and assigning them default values if they are null. Here is the implementation in the NullHandler class: public static class NullHandler { public static void PopulateNullFields<T>(T obj) { var fields...
Given an array of integers arr: Write a function flip(arr, k) that reverses the order of the first k elements in the array arr. Write a function pancakeSort(arr) that sorts and returns the input array. You are allowed to use only the function flip you wrote in the first step in order to make changes in the array. Exam...
I have this interface for all strategies: type PrintStrategy interface { Print() error } of two types: type ConsoleStrategy struct{} type FileStrategy struct { DestinationFilePath string } with two concrete implementations of strategy: func (c *ConsoleStrategy) Print() error { fmt.Println("ConsoleStrateg...
I wrote this code to get all possible magic squares that can be made with a list you put in. The only contraints are that the count of numbers is a square and that each number is unique. It even works for complex numbers. I dont know how good the performance is, it needs about 1.5 to 2hours to find all 7040 4*4 magic s...
Let me start with a litle bit of context. I have Spheres, a large pandas DataFrame with positions and radius of multiple spheres during time. (in real life 10 000 spheres and 10 000 time steps, for now 100 spheres and 100 time steps) The spheres are grouped using a label. Multiple spheres can share the same label, and ...
The core of my program are the following lines import numpy as np import time I, J = np.random.randn(20000,800), np.random.randn(10000,800) d = np.zeros((len(I),1)) for j in range(len(J)): t0 = time.time() # Compute distance matrix_j = np.array([J[j]]).T*np.array([J[j]]) for i in range(len(I)): ...
Below is a file parser for old style nuget package configuration files. The Parallel.ForEach is probably overkill; in most cases its fast enough without. However, when using the parallel loop, can I avoid the need for the lock / shared list? class Program { private static readonly object _lock = new Object(); ...
I'm trying to create a program that will try to build a target string character by character by generating random characters. I have come up with the following Nodejs program with a little bit of Google help: const args = process.argv.slice(2) const targetWord = args[0] let builtWord = '' function getRandomChar() { ...
I was given a task to read JSON from a URL and then parse it in python. Each field will be assigned to a variable to store the value. The value will then be stored into postgres table. Example of JSON { "forecasts": [ { "class": "fod_long_range_daily", "expire_time_gmt": 1525126617, "night": { "fcst_va...
I've written a program following the instructions of an exam paper. There are no solutions available so I would appreciate a feedback. I'm concerned with main in particular (I've already posted a similar question here). I've tried to solve the problem as I've seen it's done in other solutions made available by our teac...
I wrote a "gradebook" program. This takes in grades for various assignments. The assignments types are weighted differently and final grade is computed at the end. The code works but I can't help but think I am being ham handed in my approach. Should I be using a dictionary instead of storing things like hw_final, la...
I have an abstract class which acts as in interface for a variety of physical models providing Electric/Magnetic Fields as the result of a number of phenomena. I'm wondering if how I've done it is a good way to do it, or if there's a better way to achieve my goals. My goals are: A common interface for returning the f...
I used to use the MemoryCache in .Net but recently read about a DB using using a linked-list, which only had to check the prefix of the list in \$O(1)\$ complexity, to time values out, as opposed to ln N; the heap-based approach that's default for variable timeout, min-heaps. I'd appreciate a review of this code; in t...
I have been trying to develop an algorithm called keep the tool needed soonest (for more information about the KTNS explanation (page 3)) but during the simulations, I have realized that it takes too much time to run. I want to decrease the running times and checking other previous questions about how to fast python co...
This is a follow up question from here. I have revised my code as per the suggestions of peer reviewers. I still feel there is lot of scope for improvement in this code. class Node(object): def __init__(self,data, next=None): self.data = data self.next = next class LinkedList(object): de...
My program inspects filenames which are delimited via underscores. So an example may be: This_is_an_example_of_my_filename.tif A counter example may be: This_is_a_very_bad_document.tif The filename should always consist of 7 distinct values within the filename. Those values are used to create an instance of a class...
I have been taking some C# online courses the last couple of weeks in order to learn programming. Since I dont have any friends that are programming I found it hard to get feedback / reviews on the code I'm writing. Sure the code is running, but how about the code quality? About the project I have created a simple Addr...
To help improve my proficiency with Java, I would like to know how should I close these FileReaders as I have come across multiple answers, and what could I do better with this block of code? /** * Returns a Vector<String> object that that can be parsed into classes. * The file arugment must specify a realative or ab...
I made a number guessing game in Python 3 using jupyter notebook. I would appreciate it a lot if I could get some feedback on my code. from random import randint randnumb = randint(1,100) guesses = 0 maxGuesses = 5 while guesses < maxGuesses: personInput = int(input('What is your guess? ')) guesses = guesses +...
I needed to port some Coldfusion code to Java that does Title Capitalization on Strings and came up with this solution. I would love it if anyone could give me some pointers as to how to make this more efficient. import org.apache.commons.text.WordUtils; import java.util.HashSet; import java.util.Set; public class Ca...
This is my Breadth First Search implementation in Python 3 that assumes cycles and finds and prints path from start to goal. Some background - Recently I've been preparing for interviews and am really focussing on writing clear and efficient code, rather than just hacking something up like I used to do. This is another...
I recently wrote a Python script to generate a random page within a Wikipedia category and its subcategories: """Generate a random page from a wikipedia category.""" import argparse import random import requests DEBUGGING = False max_depth = 4 current_depth = 0 header = "Garrett Credi's Random Page Bot(Contact @ gcc@...
I'm currently working on a large web application with numerous routes. Currently, our routes are in one large list in a single JSON file. We recently ran into a problem due to the precedence of params being set from top to bottom in the file. This question details the issue we encountered further: Node.js Express ro...
This is my Python 3 code to generate text using a Markov chain. The chain first randomly selects a word from a text file. Out of all the occurrences of that word in the text file, the program finds the most populer next word for the first randomly selected word. It continues the process to form a very understandable te...
C++ doesn't (yet) have a 'map' higher-order function, certainly not one which applies to a compile-time sequence of values like a tuple. We have std::transform, and there's an equivalent of it for tuples listed on SO, but that's iterator-based, and anyway - I don't want to use any reference to the output. I want to pas...
I want to collect errors and its causes by defining custom errors (HTTP status 40x & 50x). For example, if user's request was bad, I want more specific reasons for the error. A customized error has its own code (not equal to HTTP status code, but related since the code format is $HTTP_STATUS (3-digit) + own code (2-di...
Let's say I have an abstract class Character that have fields health and maxHealth. maxHealth differs between subclasses. However, the first way I implemented it the health is always initialized as equals to maxHealth. public abstract class Character { protected Vector position; protected int health; protected i...
Using Entity Framework we have a number of entities, which we want to hide from the rest of the calling code to remove the direct dependency on the database. We're doing so by using DTOs, which for the most part are identical to the entities. We also have an abstract generic provider and persister pattern which handle ...
I'm new to programming and especially new to object oriented programming. I have built a web scraper using functional programming and am trying to build another using OOP principles. The overall idea for this scraper is I give it a url, it searches and retrieves all urls on that page, stores them in a set and as it che...
I was reading on this page about using a thread, catching an exception, and notifying the calling thread. The answer suggested Queue, but in the comments it states: Queue is not the best vehicle to communicate an error back, unless you want to have a full queue of them. A much better construct is threading.Event()...
I was answering a question that led down a rabbit hole of creating an EnumValueObject with [Flags] capabilities. I started with a simple EnumValuObject implementation: public abstract class EnumValueObject { public abstract string Name { get; } public abstract int Value { get; } public override bool Equa...
I'm looking for any possible improvements that could be made to run the mysql piece of code faster. I created a simple test winform application that creates two docker databases : Sqlserver on linux latest Mysql 8.0.11 Once the instances are created, it creates a similar table on both. I then use a stored procedure t...
I'm trying to configure security exceptions to all JavaScript/CSS of my pages. I need to login to access the JSP files, except the login page, but all pages needs your resources so the folders must be access-free. .csrf().disable() .authorizeRequests() .antMatchers("/login*").anonymous() .antMatchers("/bower_components...
Using Java 8, I'd like to sequence my eithers using a Collector: Sequencing a stream of eithers means for me: If there's at least one left either inside the stream, I expect the Collector to return the first left either. If the eithers in the stream are exclusively right, I expect the Collector to return a list of eac...
As much as it hurts, I've been tasked with writing a script that prepends integration, QA, etc. environment segments to anchor href attributes that link to a series of sites within two specific domains. Since we can't be certain of adherence to the requirement that content authors always use production URLs (without th...
Is there a "best" or more suitable markup to home sliders? I have the following markup. Since my sliders are related to articles, I decided to put article as the main container. Note: I am using Owl Slider to convert what is inside .home-slider actually in a slider. <section class="home-slider"> <!-- Slide One --> ...
There are times when I want to run a one-off executable on an end-user's machine that cleans up after itself, i.e. deletes itself without a trace. An exe can't delete itself because an exe can't be deleted while it's running. However, a batch file can delete itself, presumably because its contents get copied so the fil...
I am taking an introductory course in java in high school, however I have some experience in python. I was tasked to find the number of times a character occurs in a string so I did this. String a = "hello"; String letter = "l"; int occurrence = a.length() - a.replace(letter, "").length(); Happy that I came up with a ...
Where I work there's two different printers being used on a daily basis, one of them prints things from a particular program, which only uses the default printer. A lot of the times, during busy periods, people forget to switch the default printer, resulting in that program using the wrong printer, which isn't suitable...
I have written REST API for random number generation using Falcon(https://falconframework.org/), just for my learning process. This is API: http "localhost:8000/random-number?min=10&max=10" This is code: class RandomNumber: def on_get(self, req, resp): """Handles GET requests""" if 'min' not in r...
1. Introduction This is for my ANN project. Each building block of ANN, neuron, has activation function which determines how to get the output given the input (see formula in on repo I linked). I have abstract class Neuron which represents a neuron in ANN. The following points have been taken into account: Not only ac...
This is my first foray into a full TypeScript program, and one I decided to do for fun and without the aid of jQuery. It is also my first time developing with the HTML canvas. That's quite a lot of firsts, and there must be things I can do better. HexCells is one of my absolute favorite games and the last version inclu...
README.md Tetris game I am working towards making a Tetris game where you can challenge an AI. Multiple parts have been finished, but a lot is still under construction. However I would like an intermediate review. The code I will post is a fully working 1 player Tetris game made with python3.6 & tkinter. If you are int...
I was reading this question, and the answer that mentioned streams, and a thought had occurred to me. In many cases (at least in my usage) I want to determine if a sequence (or IEnumerable) has at least a certain number of elements, or has no more than a certain number, etc, that all match a predicate. As it stands now...
I'm working my way through the Rust Book: Ch.8 Challenge: Using a hash map and vectors, create a text interface to allow a user to add employee names to a department in the company. For example, “Add Sally to Engineering” or “Add Amir to Sales”. Then let the user retrieve a list of all people in a department or all pe...
Goal: Writing more readable tests. I have a couple of functions, which basically merge and converts two lists of Datasets together, written using Scala and Spark. Each of these Datasets has a lot of fields inside it. For testing, I'm creating three Datasets: New records, existing records, and expected result. The probl...
I've created a class that implements the native SessionHandlerInterface (with added PHP v7+ functionality) while adding some minor security features. My main goal was to maintain native methods for session handling while transparently adding the following features: Minor protection from session-hijacking by using clie...