instruction stringlengths 71 95.1k |
|---|
preface: I have a part of my code that is repeated more than once and I want to create a generic method or follow a design pattern to make the code cleaner.
What I'm trying to achieve is:
I have a JSON array each array represents a different type of employee.
I want to sort them by joiningDate then convert each List t... |
Looking around for modern Crypto libraries.
Could not find anything good.
I know I probably did this all wrong so work with me here. There will be four different reviews for four structures that build on each other:
Hashing
Hashed Key
Password Key
Salted Challenge Response
This is the hashing code and provides a simp... |
Looking around for modern Crypto libraries.
Could not find anything good.
I know I probably did this all wrong so work with me here. There will be four different reviews for four structures that build on each other:
Hashing
Hashed Key
Password Key
Salted Challenge Response
The data structures and implementation prese... |
Looking around for modern Crypto libraries.
Could not find anything good.
I know I probably did this all wrong so work with me here. There will be four different reviews for four structures that build on each other:
Hashing
Hashed Key
Password Key
Salted Challenge Response
This review is for an implementation of pbkd... |
Looking around for modern Crypto libraries.
Could not find anything good.
I know I probably did this all wrong so work with me here. There will be four different reviews for four structures that build on each other:
Hashing
Hashed Key
Password Key
Salted Challenge Response
This is an implementation of the scram proto... |
Is it better to validate and put an array value into a variable at the top of a file or to check the array value directly right before output in the file?
I work at a WordPress shop and we have a function that some developers commonly use to check the value of indexes in an array of custom field values:
//Check if an a... |
I normally program in a linux vm and decided to do some machine learning with my webcam when I realized the vm didn't have access to my camera hardware.
That kicked-off a mini project to create a plug-and-play module to access the webcam in a browser and redirect through a Go backend so I could work around the limitati... |
The setup is that I have a vector of a class, and I need to sort it by the quantity of a data member value, not the value itself. The below code exhibits the correct behavior, and part of that behavior is "stable" sorting where the order of elements should be preserved when possible.
Between the /*** Starting here ***/... |
I wrote a some what "simple" module to retain ETS tables should the owner crash. I think it's small enough for review; big enough to make enough mistakes. Honestly I'm a hobbyist programmer aiming for production code. I will take any criticism to get me closer.
More logging? Use of spec()? Anything.
Thank you.
ets_mana... |
I'm currently designing a class template to represent scientific notation or a floating-point number system. There are currently 4 distinct types: BIN, DEC, OCT, & HEX. This could easily be expanded by the user.
This class utilizes some of the power of C++17 or greater such as scoped-enums, lambdas, string_view, and re... |
I have a component that displays a bunch of selectable options in a single row. It takes a pageSize prop from the parent component due to responsiveness requirements.
If the pageSize prop ever changes, I need to reset the currentPage (currently active page), which is held in state, to 0.
class OptionsRow extends React.... |
I am new to coding and looking for a few pointers on how I can improve my first project.
At work, I often need to create Medicare Beneficiary Identifiers (MBI) when creating test patients with Medicare coverage, and have to look up the format every time. I thought creating an MBI generator would be a great first projec... |
Good day. My code works but I think there is a better way to do this. Like string pattern or string manipulation. I'm not yet familiar with both terms.
The goal is to get "=A1-A2-B3-D4-WHATEVER STRING=". From array of strings.
The code is :
string[] arr = { "A1", "A2", "B3", "D4", "WHATEVER STRING"}; // can be any stri... |
I'm using PHP, I have a class that generates an id based on the calling class, so the id of the class won't change after it has been initialised, now I'm wondering which of my two methods is preferrable.
Set the id in the constructor
Generate the id when asked for
/* Set the id in the constructor */
abstract class ... |
It's a web project. The code is working. The question is a design pattern question to write code that's more elegant, you know.
I've created a Codepen of this question.
I created a css grid WITHOUT using 'grid' but using float and clear.
I know such project works better written in React but it's just a try.
The grid I'... |
While working on the following leetcode problem: https://leetcode.com/problems/top-k-frequent-elements/ I used a Priority Queu implementation in Ruby. I have learned how to implement a Priority Queu in Java in Robert Sedgewick's Algorithms book. When inserting Hashes into the Priority Queue for example { 1 => 3} this ... |
I need to know whether I have implemented Strategy pattern correctly for below 3 classes provided to me for 2 tasks.1) Report Generation 2) Movie Type.
Below 3 classes were provided to me
Rental.java
Movie.java
Customer.java
public class Rental {
private Movie _movie;
private int _daysRented;
public Rental(Movie mo... |
I have a list of rescues for ambulance drivers in different states that are displayed on a kanban board. My JSON object is divided by the status of the rescues, and then grouped by driver. The structure is like this:
--Status (unassigned/assigned/arrived/rescued)
----Driver group
-------Rescue list
The rescues have a d... |
I have written a selection sort code in java. I know its very elementary algorithm, but since i am learning, so wanted your input about the quality of the code. Please have a look at the code:
package selection_sort;
import java.util.Scanner;
public class SelectionSort {
int [] arrayToBeSorted;
Scanner scan=new Scann... |
I want to test my CRUD operation to a MySql database (I use dapper as my ORM).
This is what I wrote with xUnit:
private IPaymentRepository paymentRepository;
private Payment testPayment;
private string connectionString = "Database=..."; //Test DB
public PaymentRepositoryTest()
{
paymentRepo... |
I need to write a CustomBasicMatrix class implementation for college.
This includes basic operations such as int and CustomBasicMatrix addition and subtraction, Transposition and iterations / const iterations.
I would like to know if there are coding conventions, or more importantly, Memory Leak / Segmentation Faults P... |
I have a "Palindrome" class that has some functions for verifying if certain things are Palindromes. For the verification, I have 2 different algorithms, one being recursive and the other iterative.
I'm happy with the algorithms however I'm unsure whether the way that I do the overloading and eventually parsing everyth... |
I'm looking for someone to really tear apart the following code I wrote for my graduate-level algorithms class. The problem was Optimal Caching, and the algorithm I'm implementing is called "Farthest in Future", which looks to see which cache item is either NOT in the request, or one who's first occurrence appears LAST... |
I built an backend using Django and the django-rest-framework and realized that a lot of the code snippets (mainly classes) are similar. Is there any better way? I tried to wrap them into a very generic class, but didn't succeed yet. This is what I mean by "similar serializers":
...
class DeviceSerializer(serializers.M... |
I'm working on a Django project for which I'll need to store the historic information of many models.
So far, I'm using the following strategy:
Memoize the relevant values in __init__.
When saving, check if a relevant value has changed.
If a relevant value has changed, save memoized values into a "history" model.
My ... |
I have started to learn Python and have chosen Conway's game of life as my first program. I would be interested in reading how to write more idiomatic Python. Also, what threw me off for some time was that everything is passed by reference and assignment of a list doesn't copy its values but copies the reference. There... |
I need to manage lists of executables Id. Each executable belongs to a capacity (obviously the list of capacities in the code is just an example).
For every capacity we need to be able to find the first executableId which is Available (ie not doing any treatment) and to modify the availability of an executable Id.
exec... |
Heyhey, I'm attempting to implement a ToggleBar control for Xamarin as there is non up to date and fully customizeable.
Now I haven't implemented too many controls and while the control is not fully implemented yet (I want to add an Icon option for the ToggleButtons later, but want to improve on the base before I devel... |
Attempting to populate HTML string-templates from untrusted input.
function sanitizer(str, i, list){
return str + (this[i] ?? '').toString()
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/'/g, ''')
.replace(/"/g, '"')
... |
The idea is to make an error handling procedure, which prints messages in DEV mode and shows MsgBox in PROD mode. Looking for any wise idea to improve it:
Public Const SET_IN_PRODUCTION = False
Sub TestMe()
On Error GoTo TestMe_Error
Debug.Print 0 / 0
Exit Sub
TestMe_Error:
StandardError Err, "TestMe... |
What I'm Doing
I'm writing a command line utility for starting Django projects and apps with custom files.
The custom files build upon what Django offers, to make sure things like a custom auth user model and the ability to read environment variables from a .env file are added to projects from outset.
Why I'm Doing It
... |
I’ve never used ResourceBundle before.
I have a simple Google Play Scraper (uses Jsoup library) which I want to customize and introduce
multilingual support.
I have some classes. First you have to get html Document to parse later.
GooglePlayConnection class (provides Connection, then I just need to invoke method get())... |
Question: Given an array numbers
$$a := [2, 7, 8, 5, 1, 6, 3, 9, 4]$$
Check the below conditions, both the conditions should be satisfied.
\begin{gather}
\text{If }a[i] > a[i-1]\text{ or if first element }a[i] > a[i+1]
\end{gather}
\begin{gather}
\text{If }a[i] > a[i+1]\text{ or if last element }a[LastIndex] > a[LastIn... |
I've validator system that validates input data before saving to DB.
So let's say I want to create new user.
We are at the service class:
package main.user;
import main.entity.User;
import main.user.validator.attributesvalidators.UserAttributesValidator;
import main.user.validator.availabilityvalidators.UserAvailabili... |
I have several hundreds gigabytes of photos, approximately half of them are duplicates. Average photo's size is about 4 MB, but some files (video) have size more than 100 MB.
I want to do the following:
Find all duplicates and move them into the separate directory - "Trash_bin".
Move all unique files into a "Unique_pi... |
Background
The function makes use of cut function offered in R's base package in order to "bin" a numeric vector into provided categories and apply, meaningful user, friendly labels.
Example
For vector:
set.seed(1); x <- runif(10)
[1] 0.26550866 0.37212390 ...
and brackets c(0.1, 0.3)
The function would return (for th... |
I have an array of log objects with log_types and dates, like this:
[
{
log_type: 'eventOne',
date: '2020-08-27T00:00:00+00:00'
},
{
log_type: 'eventOne',
date: '2020-08-27T00:00:00+00:00'
},
{
log_type: 'eventTwo',
date: '2020-08-27T00:00:00+00:00'
},
{
log_type: 'eventTwo',
... |
This is something I've done a few times, but I've found it to feel a bit error-prone with so many conditions, and am wondering if anyone can point me in the direction of a cleaner way. This is a PATCH route for editing a user. Super admin and admin users are both able to change other users (with some limitations) while... |
I have a method which checks all of its surrounding squares and returns the number of bombs around it. But it's really long code and ugly, so can it be shorten?
final int MINE =10
for (int x = 0; x < counts.length; x++) {
for (int y = 0; y < counts[0].length; y++) {
if (counts[x][y] != MINE) {
int Minesear... |
I have a bunch of JSON records, each record with a varying degree of completeness. In other words, record A may contain keys not in record B, and vice-versa. To get a better understanding of the data within, I have created a function to take N number of records and merge them together, creating one single frankenstein ... |
I'm trying to automate the CSS I write by developing SASS files I can reuse. I want to create a utility SASS file for padding and came up with the following.
// Variables to set the amount of padding
$_1: 0.25rem !default;
$_2: 0.5rem !default;
$_3: 1rem !default;
$_4: 1.5rem !default;
$_5: 3rem !default;
// Variou... |
I still write login system in Go(Golang) using cookies.But my system is still not secure enough.Can you review my code and provide some suggestions on how to improve the security?Previous question.
Main file:
package main
import (
"crypto/rand"
"encoding/base64"
"fmt"
"golang.org/x/crypto/bcrypt"
"... |
I have code that basically is the same, but depending on the number of arguments you provide (up to 5), it will operate with them in a very repetitive way. I have the feeling that this can be optimized in some way, since maintaining and creating all the overloads by hand is a tedious and error-prone task.
The code is 5... |
I wanted to know If there was a way to make it more versatile or shorter/simpler. Here's the code:
// Take only std::byte parameter and return an unsigned integral
constexpr auto bytes_to_uint(std::same_as<std::byte> auto... bytes) -> std::unsigned_integral auto {
constexpr auto N = sizeof...(bytes);
// Integr... |
I have a longer Macro has sub functions opening many different Workbooks, takes the data, and pastes into a Destination Workbook through arrays and .value. There are also a few functions to bring over title and data value information.
However, the macro seems to get stuck for a few seconds every time a source Workbook... |
Preliminary rant:
System.Collections.Generic.KeyNotFoundException : The given key was not present in the dictionary.
Oh. My.
So I finally got fed up with how default exception information is beyond useless.
For a part of the project I will mostly no longer use the this[TKey key] property to access my Dictionaryies but ... |
I have just started reading the GO4 book to learn the OOD concepts.
In order to practice the Prototype pattern, I implemented a small example (the idea for colored shapes was taken from "refactoring.guru"). Following is my code with some questions beneath.
Prototype definition:
enum class Shape
{
Circle,
Rectan... |
#include <cstring>
#include <map>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <vector>
#include <filesystem>
#include <errno.h>
#include <bits/stdc++.h>
std::string USERDIR = getenv("HOME");
std::string ALIASFILE =... |
So i got an task from school.
Which ask's me to write a program tad creates an 2d array with 11 rows and 5 columns.
In which the first column starts with 2.0 and increments by 0.1 all the way up to 3.0.
Then in next column it should be devided by 1 so if x is 2.0 then 1 / x and goes trough all 11 rows.
then in next col... |
Posting my code for LeetCode's LRU Cache, if you'd like to review, please do so, thank you for your time!
Problem
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.
get(key) - Get the value (will always be positive) of the key if the ke... |
This code review is presented in 3 questions due to the amount of code:
Part A (this question) contains the Lexical Analyzer and the main portion of the unit test code.
Part B contains the lower level unit tests called in Part A
Part C contains common unit test code that is included in all of the unit tests to be writ... |
This review is presented in 3 questions due to the amount of code:
Part A contains the Lexical Analyzer and the main portion of the unit test code.
Part B (this question) contains the lower level unit tests called in Part A
Part C contains common unit test code that is included in all of the unit tests to be written.
... |
This review is presented in 3 questions due to the amount of code:
Part A contains the Lexical Analyzer and the main portion of the unit test code.
Part B contains the lower level unit tests called in Part A
Part C (this question) contains common unit test code that is included in all of the unit tests to be written.
... |
I am new assembly programming in Linux (x86_64) and I want to make sure that I am programing in a correct way. I wrote a program that just takes an input from the user and then writes his input to stdout
SYS_WRITE equ 1 ; write text to stdout
SYS_READ equ 0 ; read text from stdin
SYS_EXIT equ 60 ; terminate the... |
I wrote some code to get 3 integers from the user. The code then prints the sum of the 3 integers. The code works as expected. I want to validate all input before doing the calculation. However, the code just doesn't feel right. Is there another approach I should be taking? It seems.. redundant. I am looking into neste... |
It is my first program in Javascript. Is there any lack or a thing to be improved? It simply increases, decreases, or reset the counter either by buttons or arrow keys.
HTML,
<h1 id="number"></h1>
<button class="btn" id="incr">Increase</button>
<button class="btn" id="reset">Reset</button>
<button class="btn" id="decr"... |
I implemented a multi-producer single consumer class, with an important restriction that once the consumer started working, it must continue its work on the same thread (the reasoning behind this is to allocate and free COM objects from a third party library, and these actions must be on the same thread according to th... |
I am using SignalR to send notifications to clients. I use IClientProxy which is a proxy for invoking hub methods.
It has 10 overload methods for SendAsync that takes parameters one by one as you see below, however, to handle this situation I have written a spagetti style method which is really weird to me.
Could you p... |
Below is the implementation for the Floyd-Warshall algorithm, which finds all-pairs shortest paths for a given weighted graph.
The function floyd_warshall takes a graph as an input, which is represented by an edge list in the form of [source, destination, weight]
The path_reconstruction function outputs the shortest pa... |
In an effort to learn Java's support for concurrency I solved a self-imposed exercise to write a Game of Life simulator in Java, running a separate thread for each cell.
Here is my code:
import java.util.*;
import java.lang.*;
interface ICell extends Runnable {
boolean retrieveGeneration(int generation);
void ... |
This is an implementation of a Color class, primarily targetting the web to be used in a Blazor app.
Color.cs
using System;
using System.Globalization;
namespace Color
{
/// <summary>
/// Represents a Color with Red, Green, Blue and Alpha channels, packed into an integer. Also contains utilities to convert bet... |
This is my first ever python project finished from start to end. This is the third iteration after posting twice before and using the feed back. This time I decided to add tkinter. Just seeing if there code in my program that could have been done better. Also I lots of code uses self and init and I can never seem to un... |
Rather embarrassingly, I have been coding for some years now, however I feel that I still write code in a very basic way. It is hard to be certain, when many companies often give coding interviews for free labour, and the internet rarely sees software development from a business side but treats it too academically fuss... |
I have this function which calculates how many seconds, mins, hours etc ago a specific time string was.
However, the way I have done it consists of a massive if statement block, and it goes through each specific time that it can reach.
Is there a better way of writing this code where it's more efficient and doesn't hav... |
In the process of learning JavaScript, I built a Google Chrome extension. It works but as I am adding more features the code is quickly getting duplicated, so I'm looking for ways to improve it.
This is the code (other parts of the extension are omitted for brevity):
let createProject = document.getElementById('cproj... |
I'm a chemistry student working on a research team and part of my job is to produce simple computational scripts that can be understood and used by members unfamiliar with Python or other languages. I was recently tasked with producing a script for creating crystal lattices of any desired 3-dimensional permutation of A... |
I have a problem with my code, because his is required a long time to be done(only when I put big numbers like 2000)...
I am trying to do the Hamming Numbers kata on codewars.com:
A Hamming number is a positive integer of the form 2i3j5k, for some non-negative integers i, j, and k.
Write a function that computes the n... |
This class works as a single instance of a worker, a worker reads from a bank of queue items from a MySQL database table, although that logic is abstracted into ScraperQueueDao class. One process runs only one worker, although many processes are spread across multiple servers.
This code is only used by me for personal ... |
Here is my little snake game which I made in c++ using the SFML library. The game is very simple. I have also included a screenshot of how the GUI looks. The files which I am loading are 30x30 colored squares. Yellow is the background. Red represents the snake. White is the cherry/fruit/prize to increase the size of th... |
Since I am trying to learn many programming languages, I created this simple Android app. What it does basically is taking a sentence phrase from an EditText ed and translate it to speech when you click the start button.
I used onActivityResult to prevent app from crashing when the EditText becomes empty.
I am sensing ... |
I'm trying to implement a Priority Search Tree(PST) following this note: http://cs.brown.edu/courses/cs252/misc/resources/lectures/pdf/notes07.pdf. For convenience, I copied the related peuso-code here:
and the note has also provided an example for creating a PST, I just copied the final tree here:
The following is m... |
After not programming in c++ for some time, I decided to write an AVL tree implementation to get back in shape (I wasn't that good anyway. Still an amateur).
Header File
bst.hpp
#pragma once
#include <iostream>
#include <utility>
namespace bst
{
template <typename T>
class BstNode
{
public:
... |
I am writing an Express.js middleware function in a TypeScript NodeJS project that uses a function from a third-party module to perform a small workload. When writing unit tests, I want to mock this third-party function. In the following code, the decodeFunction parameter is what I used as a seam to inject the dependen... |
Description
I've created simple SBT plugin which enables creating Helm Charts
The main reasons:
in Helm it is impossible to 'fetch' external files: https://github.com/helm/helm/issues/3276 which is very cumbersome when dealing with applications that are packaged multiple times with different configurations.
want to pa... |
i have made simple python login nothing impressive but i have the feeling that i could have done it differently.
I saw some people saying that i should use text files but i tried and i didn't quite work out with iteration .
How would you approach it using a text file ?
print('WELCOME USER , Please Enter Your Login Info... |
This is exercise 2.3.24. from the book Computer Science An Interdisciplinary Approach by Sedgewick & Wayne:
Modify Beckett to print the Gray code.
Beckett refers to the following program within the text:
public class Beckett
{
public static void moves(int n, boolean enter)
{
if (n == 0) return;
... |
I'm trying to add students to Google Classrooms ('Courses') from a Google Sheet with code below (function AddStudents).
It's very slow and, if I do too many, it exceeds allowed execution time. Is there anything that I can do to speed it up?
function AddStudent(argStudent, argCourseCode) {
Classroom.Courses.Students.c... |
The following source code is a solution to the Marching Square problem.
The explanation of using random numbers in ambiguous cases can be found here.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
namespace G__Marching_Sqaure
{
public static class StaticRandomNumber
... |
Brief introduction: so the point of the question is that the author doesn't really talk about good or bad code quality and I really wanted some feedback to have a grasp of how the code for others to read should look like. I mean, for the very first solution of the task I would check different parameters manually just t... |
I have the following Ruby method.
def get_status(creds)
client = create_client(creds)
status = client.account_status
client.close_session
status
end
Usually I optimize this kind of code by using tap or yield_self.
I have come up with a way to use these, but it doesn't seem like the nicest way to optimize it.
d... |
I'm new to react and am building a basic react app and have just built a basic area where navigation links render on a page but wonder whether my current start could be optimised - for example, I wonder whether an area like this:
render() {
return (
<Root navLinks={this.state.navLinks}></Root>
);
}
... |
Assessment Question: Print an array of size n*n, with border as 1's and rest of the element as 0's.
Sample Input: 5
Sample Output:
[[1 1 1 1 1]
[1 0 0 0 1]
[1 0 0 0 1]
[1 0 0 0 1]
[1 1 1 1 1]]
Here is my solution:
import numpy as np
n = int(input("Enter a number:"))
np_box = np.zeros([n, n], dtype='int')
np_box[:,... |
I built a quite simple webpage to display a random quote from an array of quotes.
I would love to have some feedback on the JS, CSS, and HTML, for example, feedback about best practices, maintainability, readability, accessibility, semantic markup, performance, or anything you can spot that could be improved.
This is i... |
Amateur c++ programmer here, working my way through the Project Euler problems (problem 4). I would love for someone to take a look at my ~40 lines of code and give suggestions on improving the effectiveness of the code, and how/what to change to better follow the general guidelines for the flow of a c++ program.
The t... |
For this graph and its vertex cover I try to compare the LP solution with the optimal and the rounded solution.
from scipy.optimize import linprog
obj = [1, 1, 1, 1, 1, 1, 1, 1]
lhs_ineq = [[ -1, -1, 0, 0, 0, 0, 0, 0],[ -1, 0, 0, -1, 0, 0, 0, 0],[ 0, -1, -1, 0, 0, 0, 0, 0],[ 0, -1, 0, 0, -1, 0, 0, 0],[ 0, 0, -1, ... |
The function below passes most test cases:
function numOfSquares(a, b) {
const isSquare = function (n) {
return n > 0 && Math.sqrt(n) % 1 === 0;
};
let squareCount = 0;
for (let i = a; i <= b; i++){
if (isSquare(i)) {
squareCount++;
}
}
return squareCount
}
... |
Background
I have a code that basically caches file. The way it works is it will first check if the file exists on the local drive and if it does if there is a flag passed called validate_file_size then it will do another check to see if the size of the file on local drive equals the size of the file on S3. if they equ... |
This code is utilized within a platform that has strict limitations on script execution time, occasionally being exceeded if there is a very large number of lines within the CSV input that is passed into this script. The script then outputs JSON by capturing the necessary data from each CSV line, and grouping data bas... |
def merge_arrays(list1, list2):
len_list1 = len(list1); len_list2 = len(list2)
merge_len = len_list1 + len_list2
merge_list = []
l1_ptr = 0
l2_ptr = 0
# import pdb; pdb.set_trace()
while(l1_ptr <= len_list1-1 and l2_ptr <= len_list2-1):
if (list1[l1_ptr] <= list2[l2_ptr]):
merge_list.append(l... |
I wrote the following x86 program to make sure I'm following the correct practices in calling a function and then exiting to the OS:
.globl _start
_start:
# Calculate 2*3 + 7*9 = 6 + 63 = 69
# The multiplication will be done with a separate function call
# Parameters passed in System V ABI
# The firs... |
I'm still new to coding and self-taught. If anyone could take a look at my code for my Ruby Hangman game and give any tips or advice whatsoever, it would be greatly appreciated. I'm trying to improve!
The game is completely functional right now, and has a save/load feature.
Repli link:
https://repl.it/@MaBuCode/hangman... |
I was told my code contains a lot of force unwrapping. I thought it's okay to do that if I am sure that the value operated won't be nil:
private var x: Int?
private var y: Int?
@IBAction func startButtonPressed(_ sender: UIButton) {
guard let numberOfRooms = selectedRooms.text, !numberOfRooms.isEmpty else {
... |
I want to wrap NSCache in a Singleton in order to use dependency injection in my code. This has resulted, rather unfortunately, in passing the type through a function parameter, and I even need two mocks for success and failure since it is a singleton instance.
I think there might be a better way, but any comments appr... |
Category Service:
public Boolean deleteCategory(int id) {
try {
Category category = categoryDao.getCategoryById(id).orElseThrow(NoSuchElementException::new);
categoryDao.deleteCategory(id);
categoryDao.moveCategoriesUp(category.getUserid(), category.getPosition());
return true;
... |
I wrote a script to reorder the columns in a CSV file in descending order and then write to another CSV file. My script needs to be able to handle several tens of millions of records, and I would like it to be as performant as possible.
This is basically a mockup of a more complex CSV transformation I would be working ... |
I used the Bootstrap v4.0.0 accordion to display my business services. Further, I created a custom post type "service" for my services (Each service is a post).
To display my services dynamically and not hardcode them, I implemented a for-loop within the WordPress while-loop which uses an enumeration to provide the num... |
Idea
After a handfull of small javascript-projects, I also wanted to work a bit with php now. I decided to create a simple contact-form. Of course, I wanted it to be as spam-save as possible, so I used some of the ideas I found online (honeypott and some sort of CAPTCHA).
I realized the CAPTCHA-idea in the following wa... |
This is web exercise 2.3.20. from the book Computer Science An Interdisciplinary Approach by Sedgewick & Wayne:
Write a recursive program that takes a command-line argument n and
plots an N-by-N Hadamard pattern where N = 2^n. Do not use an array. A
1-by-1 Hadamard pattern is a single black square. In general a
2N-by... |
I'm drawing a square on a window using an implementation of Xlib. I put a colored pixel with my_pixel_put at a specific (x,y) coordinate.
Code to review
#define LWST_VAL 200
#define HGHST_VAL 400
int main()
{
t_data img; //image data
int x = LWST_VAL, y = LWST_VAL;
// steps creating a window, creatin... |
I want to move two element of my array to the beginning.
This solution works but I would like to know a better approach since using sort() twice is probably not the best.
Array Input:
colors = [{name: yellow}, {name: blue}, {name: green}, {name: red}, {name: orange}]
JS Function:
sort(){
let green= colors.find(color=>... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.