instruction stringlengths 71 71.9k |
|---|
I need to extract some data from the environment variables using Go. This data can be string, boolean or integer, so I ended up writing three functions.
package main
import (
"fmt"
"os"
"strconv"
)
func getStrEnv(key string) string {
val := os.Getenv(key)
if val == "" {
panic(fmt.Sprintf("s... |
Here is working code to get N closest points to some reference point.
Please help to improve it, specifically by commenting on my use of std algorithms and vectors/iterators manipulations.
Nearest.h
#pragma once
#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
namespace nearest {
struct P... |
<?php
define('AES_256_CBC', 'aes-256-cbc');
// both stored in a file on server
$encryption_key = openssl_random_pseudo_bytes(32);
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length(AES_256_CBC));
$user_id = 1123;
$exp = time() + (365 * 24 * 60 * 60);
$data = [
"user_id" => $user_id,
"exp" ... |
It takes my code over 700 seconds to solve simple puzzle:
2 7 11 5
13 0 9 4
14 1 8 6
10 3 12 15
My function findSolution(puzzle, minH) takes puzzle as an array and minimal h parameter which has to be found.
I'm using A* with Manhattan Distance heuristic function. G is step number and h is Manhattan Distance.
... |
This ObjectSet container adds new Objects with lowest possible unique ID. My implementation uses std::set for its sorting, but this convenience may not be required.
My two main questions are:
Is std::set generally a good and preferred solution for this problem?
In case of using std::set, can ObjectSet::minId be implem... |
Simple function which returns a text representation for numbers in range [1...1000].
N100 = 'hundred'
N1000 = 'one thousand'
N1_9 = [
'one', 'two', 'three',
'four', 'five', 'six',
'seven', 'eight', 'nine',
]
N10_19 = [
'ten', 'eleven', 'twelve',
'thirteen', 'fourteen', 'fifteen',
'sixteen', 'sev... |
I read the following question: Searching an element in a sorted array and I thought that I could give it a try in Python.
Given a sorted list of integers and an integer. Return the (index) bounds of the sequence of this element in the list.
Example:
l = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 4, 4, 6, 7, 8, 9, 9, 9, 9]
0 not ... |
I'm calculating how many possibilities there are to fit \$n\$ identical bottles inside \$k\$ crates of various capacities.
n = Number of bottles
k = Number of crates
K = List of the number of bottles each crate can fit
Each crate may be filled with any number of bottles up to \$K_i\$, including being empty.
This is a... |
I am trying to create a fully async example of a client and server using SSL.
I think these are the required assumptions:
Connecting may require socket readability and writeability notifications.
When the socket is readable, SSL_write may need to be called depending on the result of the last call to SSL_write.
When th... |
For a server-side Java application I want to have a random number generator. I'm using the ISAAC algorithm from Apache Commons Math 3 because it is both cryptographically strong and fast. I have written the following code to initialise the generator:
public class ThreadLocalRandomGenerator {
private static ThreadLo... |
Design a program that finds all numbers from 1 to 1000 whose prime factors, when added together, sum up to a prime number (for example, 12 has prime factors of 2, 2, and 3, which sum to 7, which is prime). Implement the code for that algorithm.
I'm pretty satisfied with what I did, but I want a review. Can I make it ... |
I would appreciate any feedback concerning my analysis of the most efficient FizzBuzz solution programmed in Ruby. I submit that a Case-statement solution is more efficient than utilizing a ConditionalIf-statement in my recent blog-post within my conclusion provided thusly:
Consequently, the predictability pattern is ... |
The OpenGL tutorial that I was following only used a single model to demonstrate various points. I wanted to draw more than one model. After some research, I came to the conclusion that I needed to create a vertex array object, once for each model, and than I can use it to access buffers and attributes for each model. ... |
I'm just getting started on the site CodeEval, and I submitted my first solution today. What I don't understand is why it's marking my (working) answer as only a "partial solution". The site doesn't seem to want to explain why my answer is only "partial", and I'm hoping someone here can explain why.
The challenge I was... |
I was reading up on implementing Graphs in Python and I came across this Essay at python.org about graphs, so I decided to implement it, but with weighted edges.
I start with arcs and their cost using list of lists and then iterate through it building a dictionary (Adjacency list format) that represents the Undirected ... |
Inspired by FizzBuzz by Brainfuck, I decided to write an interpreter for Brainfuck. It:
Removes all non-command characters
Optimizes commands (removing +- and <> pairs)
Executes each command one-by-one
Speed:
FizzBuzz by Brainfuck: about 10 milliseconds
Code:
BFInterpreter.java
import java.io.IOException;
import ja... |
I've been trying to learn the basics of Javascript, so this afternoon I put together a small JavaFX application that has a raw text area on the left, and an HTML rendering on the right:
public class Fifty extends Application {
private String filePath = null;
private TextArea text;
public void init() throws... |
I have a MySQL database, with a table called articles. There is a column in articles for its id, name, date_created, etc.
I want to create a page for each article, for example:
example.com/article.php?id=1
example.com/article.php?id=2
...
My code works right now, but is there anything I should do differently? I'm wor... |
Please review the code below where thread Odd prints all odd numbers from 1 to 9 and thread Even prints all even numbers from 2 to 8. I tested it and it works but can we improve it from design or performance perspective?
To print odd
public class Odd implements Runnable{
private Monitor sharedObject;
public Odd(Monit... |
My attempt at a simulation of one-handed Solitaire. Any comments welcome!
// Basic implementation of one handed solitaire by Andrew Ewen.
//
// Not sure if working correctly as it wins roughly 1/90 games whereas wikipedia states it
// is closer to 1/140.
function Card (suit, rank) {
this.suit = suit;
this.ran... |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE ScopedTypeVariables #-}
data E a
= E1
| E2
| E3 a
data L
data R
f :: IO (Maybe (E L))
f =
(undefined :: IO Bool) >>= \case
False -> return (Just E1)
True ->
(undefined :: IO Bool) >>= \case
False -> return (Just E2)
True ->
... |
I've written a program that counts the number of inversions using a Divide and Conquer algorithm, written in C++11.
#include <iostream>
#include <tuple>
#include <vector>
using IntVec = std::vector<int>;
std::tuple<IntVec, long long> count_inv(IntVec xs);
std::tuple<IntVec, long long> count_split_inv(IntVec xs, IntVe... |
I'm happy to hear thoughts and ideas on structure/performance/testing/whatever and multi-threading, which I haven't gotten into yet with Python.
Latest code here. Assignment file and a few test files included in the folder.
import sys
import unittest
from copy import deepcopy
class PivotMaker:
pass
class PivotF... |
I would like to know if there is anything that I missed following the GRASP patterns.
The Main Controller class:
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace ConsoleApplication1
{
public class SnakeGame
{
private bool GameIsPlaying... |
I've written this a short time ago. Do you see anywhere I can improve my logic? This is my first python script.
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
from ftplib import FTP # ftplib comes with the py install
class Ftp:
def __init__(self, hostname, username, password, port=21):
print '\nCo... |
What would be the best way to refactor following method?
public void AddOrUpdateDesign(DesignInformation designInformation,
CommonTransformerProperties commonTransformerProperties,
SecondaryWindings secondaryWindings,
CapacitorVoltage... |
Continuing from my last question I have now implemented a Double Linked list. All the code (with tests) is also available on GitHub.
DobLinkedList.h
#include <stdio.h>
#include <stdbool.h>
#ifndef DobLINKEDLIST_H
#define DobLINKEDLIST_H
#ifdef __cplusplus
extern "C" {
#endif
typedef struct DobLinkedListNode {
... |
I was in need of a function that could check a string against a certain pattern at compile-time. The pattern can contain any of the commonly known wildcards: ?, * and +.
? - match any character.
* - match any sequence of characters, including the empty string.
+ - equal to ?*
I'm not sure how to test my code for erro... |
I am trying out for the first time knockoutjs and babeljs and have a question on how to do computed observables properly. Both fullName and fullNameComp properties are updated whenever firstName and lastName changes so not sure about pros/cons:
<h2>employee</h2>
<input type="text" data-bind="value: firstName, valueUpd... |
I wrote implementation of LRU in java and want to know if it can be improved further both in space and time complexity.
Input: Number of frames and reference string for pages.
Output: Number of page faults.
Also I am a little skeptical about its correctness because I got 6/10 in my practical lab.
Kindly ignore OOP's a... |
I have read this and I want to know how the solution that I came up with in my interview compares with the top solution.
public static String reverseWords(String s) {
if (s == null) return null;
else if (s.equals("")) return "";
else {
s = s.trim();
int index;
for (index = 0; index <... |
How can I make my code more pythonic ? I definitely think there is a way to make this code a lot more readable and clear + shorter...
But I haven't found an effective way. Any techniques I can use to make it more concise and clear?
#!/usr/bin/env python
import requests
import socket
import random
import re
import time
... |
I wrote this little helper to render a table, however, working with nested content_tag is messy.
def semantic_table(table_headers)
content_tag(:table, class: 'ui basic striped table') do
(content_tag :thead do
content_tag(:tr) do
table_headers.each { |h| concat content_tag(:th, h) }
... |
I made a simple hash table and I was wondering if there was any way to increase the efficiency of search times. My table class is called Dictionary, because C# has tainted me.
The way I set this up is that Dictionary has an array of Buckets, a modified linked list whose Nodes store string keys as well as whatever other... |
Similar to the previous post Brainfuck Interpreter: Slower than a Snail?, it runs BF in java. The only difference is that the converter will convert the BF code into a compilable and fairly readable Java code, and run it.
Example:
BF code:
++++++++++[>++++++++++<-]> Initialize 100 (number of times to perform FizzBuzz)... |
This method has three parameters. If the extension is not null, for each item in list try to add extension to main text in a way that length of result doesn't exceed 20.
I wrote this code, but I don't like its style. I like to use Linq and newer styles for doing this, in order to make it shorter.
public string AddExten... |
I'm new to programming (just about 2 months), and have been trying to learn as much as I can as quickly as I can.
I made a little Hangman game as a practice project this weekend. It doesn't have visuals — the user is allowed 5 strikes. I used the enable1.txt list of words.
Anyway, I was hoping to get some feedback on ... |
A long time ago I created a script for moving up directories very quickly in the command line using the command up. You can find usage notes here.
It's a very simple script with just 8 lines of source code, as follows:
if [ -z "$1" ]; then
cd ..
else
for i in `seq 1 $1`;
do
cd ..
done
fi
I've ... |
I wanted to keep my API request logic separate form the controller logic. I therefore make use of a separate model (EmailChecker) that creates an instance of this class via EmailChecker.new(params).
Then I can check the new instance with valid?.
When it returns false I grep the errors and return it. This example only c... |
I've decided to make this module of a dialog, sort of like talking to NPCs in games, like this for example.
I've creating the visuals of the window using the code from this post, works pretty well.
Here's an example:
I've created a Manager class to manage those pop-ups, and the obvious PopUpDialog class.
Here's the Ma... |
def guessr():
'''Application that generates 5 numbers which a user enters a number as a guess to match any of the number generated
by the application, if you is able to guess one of the numbers correct, user has won, else user lost'''
from random import randint
print 'Welcome to the Number Guesser App... |
I know Swift isn't exactly meant to be used to write your classic stdin to stdout scripts, and that Python, Ruby, Perl, bash, awk, and friends are much better in this area, but I'd still like to see how well it can be done.
The problem I chose is: Read from standard input, and write to standard output a space-separated... |
This is my second algorithm and I will try to make it as simple for you to understand how it works. It is pretty expensive and I'd like to make it more efficient.
.
It works by splitting a square into 4 sides and then by determining if an edge is within a side (which is a triangle). Then collision can respond by using... |
I'm still somewhat new to C, so pardon me for any silly mistakes I've made.
I'm trying to convert video frames into Minecraft map colors using JNI and FFmpeg's av (and swscale) libraries. The code works below but it's sluggish and I'm going to assume it's prone to the branch prediction problem.
The Minecraft map data i... |
I am currently teaching myself C++ in my spare time. I created the below "game" to simulate combat between an army of humans and an army of skeletons. Is there a simpler or better way of creating this game? I would love for someone to "improve" my code so I can get a better idea of how to use C++.
I think a major impro... |
This script, once added to the Windows Scheduler, automatically creates a backup of your Google Chrome bookmarks.
import shutil
import os
import datetime
def setup():
print ('Enter your Chrome bookmark directory.')
print ('Standard one is: C:\\Users\\<USER>\\AppData\\Local\\Google\\Chrome\\User Data\\Default'... |
I'm new to unit testing and I'm curious if anyone can see any problems with my approach below. Basically I want to test the Add function. To do this I am creating a new Account object, passing that to the Add function, retrieving that account and finally comparing the retrieved objects values to hard coded values.
I'... |
I was working through Cracking The Coding interview, and I couldn't wrap my brain around their solution to one of the problems, so I ended up coming up with my own that, IMHO, is a lot cleaner and easier to read. Would love your feedback. Here is the actual problem:
"A binary search tree was created by traversing throu... |
I made this as a personal challenge. It seems to work fine as I can't find any bugs and am happy with how it runs, but I am interested in what I should do to make the code more professional.
I think the draw() function can be replaced with two for loops but I could never get it working. The code for the input by each o... |
Today is my first time working with GUI, so I'm really interested in the best ways of handling various events to get the best habits from the jump. Most of the GUI-related code for this project was generated by Netbeans's layout manager, although I tried to rip out as many of the meta tags that I could, did imports whe... |
I am currently creating a Multiplayer Game using node.js and web sockets. The client side is receiving the positional information and applying it to all the players on the client side. Each client stores a list of all game elements.
The main issue I am experiencing at the moment is a large amount of Garbage Collection... |
I have an ASP.NET web-client and many WCF services. I used it this way:
public class UserController
{
private Service1Client _service1Client = new Service1Client();
private Service2Client _service2Client = new Service2Client();
public JsonResult HasDebts()
{
var user = _service1Client.GetUser... |
Problem
Count the number of matching nodes in the subtree rooted at some node n.
Solution
from collections import namedtuple
Node = namedtuple('Node', 'key, left, right')
def build_tree(inorder, preorder):
"""Builds a Binary Tree from given inorder and preorder traversal.
Steps:
1. Take the first element ... |
How do I write this function more efficient? My class names always contain modell and essentially, only the numbers are changing. Is it right that I get a better performance if I update the numbers instead of adding and removing classes ?
So basically: modell[1], modell[2], ...
jQuery(document).ready(function(){
... |
I've implemented simple +-*/ calculator in WPF. I know that here are few implementations of the same thing, but each is different, with different advantages or disadvantages against this one. Can you suggest me, what could be improved in my code?
// calculator operations
public enum CalcOperator
{
None,
Plus,
... |
I have this before_action method :
def convert_duration_reminder
allowed_duration_units = %(hour day)
if allowed_duration_units.include? params[:store][:store_setting_attributes][:reminder_unit]
store_settings_params = params[:store][:store_setting_attributes]
@duration_reminder = store_settings_p... |
This code snippet is about asking Windows for the highest possible execution priority. Basically, we have to ask for real-time priority class for the entire process, after which each thread has to ask for real-time thread priorities. However, since Windows Vista, whatever is the program that needs the real-time priorit... |
I've tried designing a Turing Machine model, it works quite well, however I think it could be confusing to maintain on in the future, and I'm not sure what of best practices. Can I get some feedback on my code?
Turing Machine Namespace
using System;
using System.Collections.Generic;
namespace TuringMachineNS
{
pub... |
I wrote a small generic implementation of a simple generic double buffer pattern, and I was wondering if it's actually thread safe or can be improved in any way.
Note: The specific part that I'm worrying about thread safety is the Swap() function.
/// <summary>
/// Simple generic double buffer implementation class
... |
I’m working in Objective-C, SKSpriteKit and am trying to create a class which will work in both OS X and iOS for flexibility.
I have just created a new protocol for my programs: <mutableDeepCopying>. I’ve implemented this protocol into NSArray and NSDictionary using categories. The MutableDeepCopying.h file is pasted b... |
I’m working in Objective-C, SKSpriteKit and am trying to create a class which will work in both OS X and iOS for flexibility.
Recently, I asked the question which asked if there was a way to create a method in a new class which automatically ran itself every frame. I was answered that it would be a good idea to use CAD... |
Suppose you are given two functions, foo and bar, and neither of them are inlined. Now, if foo calls for bar and bar calls for called_from, bar receives the address of the caller, that is, the address of foo. I know that there is no real need for such computation as it is always possible to simply pass an enumeration t... |
Is this an acceptable approach to update WPF MainWindow from an async task, using events thrown from a public static class?
In MainWindow.cs, I subscribe to UI.TaskCompleted event
In UI.cs, I subscribe to AsyncTaskActions.TaskCompleted event
Using this pattern, AsyncTaskActions.TaskCompleted is raised when an async ... |
A similar question must have been asked a thousand times, but for the life of me I can't figure this out. I am new to Java and I want to create a programme that asks a user for his or her height and weight, and calculate the corresponding BMI. I want to throw exceptions for the wrong input (has to be a double, non-nega... |
I'm using EF7 with In-Memory database and xUnit for repository testing. I'd like to know if it's a good practice initializing the database in this manner for reuse it in every test method, specifically through the Initialize() method:
private Context _context;
private BrandsRepository _repository;
private void Initiali... |
I am using the below code to execute a MySQL query in PHP.
$cus_id = '1';
$query = new QUERY();
$clause = "SELECT * FROM customers WHERE cus_id=:cus_id AND status='ACTIVE'";
$params = array('cus_id'=>$cus_id);
$result = $query->run($clause, $params)->fetchAll();
Is it secure enough, or do I need to bind the static var... |
Let's say I have \$5\$ apples, thus \$n = 5\$. I have three bags (\$k = 3\$), each having the capacities of \$4\$, \$4\$ and \$2\$:
$$c = { \{4, 4, 2 \}}$$
I'd like to calculate the number of ways the \$5\$ apples can be distributed into those bags; each bag can be empty. The results for this example would be following... |
This class seems to be able to represent the data stored in any possible database table:
public class DbTable {
private Set<Map<String, Object>> tblData = new HashSet<Map<String, Object>>();
public DbTable(Connection dbConn, String tblName) throws Exception {
PreparedStatement prpStmt = dbConn.prepare... |
The foldRight and foldLeft methods for Scala Streams cannot terminate early, so here is my attempt to provide that functionality through the "enrich my library" pattern:
implicit class StreamWithLazyFold[A](s: Stream[A]) {
def foldLeft1[B](z: B)(f: (B, A) => (B, Boolean)): B = s match {
case _ if s.isEmpty... |
I have the following code which does 2 things:
Return a scanned fingerprint as base64
Store this print as bitmap
While the code works most of the time, sometimes an invalid bitmap is saved (I can't open the file). I think there are some improvements (padding?) that can counter this strange behavior. The 'firstPixel' ... |
I'm currently reading a book and watching some tutorials about PHP with MySQL (PDO), but it is not clear where to put certain things - where to put some code, should I put the connection to the database within try-catch and so on.
So, I'll explain how I started my project and if you could tell me if this is wrong or i... |
I wrote a wrapper class in PHP to use Telegram bot API. What do you think about it?
I used this class in some projects and it doesn't have any problem but I want to know if it is optimized?
<?php
/**
* A wrapper class for telegram bot api
* you can find source code in https://github.com/smoqadam/php-telegram-bot
*
... |
I am consuming data from an API that reads from a SharePoint list. The API is basically this:
IList<Dictionary<string,string>> GetListData(string listName);
So the data is a list of dictionaries - each dictionary containing value-pairs (column name, column value) for a "row" in the list.
I need to group over the resul... |
I have written the code for a genetic algorithm and have the crossover function, mutation function, parent selector function and a function to transfer genes. Now I want to put it all together and would like to know if the following code is good programming practice or not.
Species Parents[popSize];
Species Children[po... |
I'm trying to figure out if I'm doing superclasses right. Also, I welcome critique on Java structure/syntax etc.
Animal.java:
public class Animal{
private static int counter = 0; // how many animals we have created (to demonstrate a static variable)
private Boolean isWild = true; // is the animal wild?
pri... |
I am working on a project with an Arduino microcontroller and a Raspberry Pi. The code will have to do the following:
If the variance calculated of the ultrasonic sensor detections exceeds 1000, a event will be sent over the serial bus starting with the prefix /E/
If a request is received on the serial bus asking for... |
I've got a Python function that takes two arguments, lat and lon. These arguments can be either scalar values (52.3) or any sort of iterable (e.g. a list or a NumPy array).
At the beginning of my function I need to check what I've been given, and convert both arguments to arrays (if needed) and check that both argument... |
Write a program to determine the mean, median, and standard deviation of a list of numbers
Count the duplicate numbers in the code, listing any that occur more than once with the number of times it occurs.
My implementation:
import math
def mean(input):
return sum(input) / float(len(input))
def median(input):
... |
This program's main function is to:
Watch a directory.
If there are new files, insert those as entries into the database.
Delete the files from the directory.
My below code runs well, but I want to optimize it and I think it needs better error handling.
import os
import time
import mysql.connector
import MySQLdb
imp... |
Please critique:
public void printTree(Node head) {
if (head == null)
return;
Queue<Node> q1 = new PriorityQueue<Node>();
Queue<Node> q2 = new PriorityQueue<Node>();
q1.add(head);
do {
while (q1.size() > 0) {
Node element = q1.poll();
System.out.print(elemen... |
My aim is to write a method which prints contents of a singly linked list in reverse order with time complexity \$O(n)\$ and space complexity \$O(\sqrt{n})\$. The best I could come up with is to store the pointers to nodes in an array and print it in reverse order.
void display_reverse(List *l)
{
int list_size = si... |
I am self-taught and trying to improve my programming skills. My project is a point-of-sale application, with lots of buttons. I am curious how improve this section of code, as I seem to be going against the DRY principle.
I have a Customer object named cust, and each customer has an ID that is set to one of 8 differe... |
I'm making an app in Excel-VBA, but when I have more than 50,000 records, my code runs very slow and the formatting takes about 33 seconds.
Application.Interactive = False
Application.EnableEvents = False
Application.ScreenUpdating = False
'--------------- Tao Bien ------------------------------------------
Dim Dulieu(... |
I have written a method to determine whether a Vector2 lies inside a polygon or outside of it. The polygon is defined by an array of clockwise vertices, p[]. It returns true if the point is inside, false otherwise.
public bool polyCheck(Vector2 v, Vector2[] p)
{
int j = p.Length-1;
bool c = false;
for(int i... |
The user can provide a JSON object to configure the plugin when they initialise it. I want those options to be available whenever a plugin action is performed.
I have read the plugin documentation but I'd like to get confirmation that I am going about this the right way.
Plugin is initialised with:
$(selector).hide_and... |
I sometimes need an object that caches some data but only for the specified amount of time. So I created a class that should handle this. The main goal was to make it generic unlike the MemoryCache and be a single object cache and not a general all-pupose cache.
ObjectCache
public class ObjectCache<T>
{
private rea... |
Ram was busy calculating the factorials of some numbers. He saw a
pattern in the number of zeros in the end of the factorial. Let \$n\$ be
the number and \$Z(n)\$ be the number of zeros in the end of the factorial
of n then for
\$x < y\$
\$Z (x) \leq Z(y)\$
i.e. the function never decreases.
He is solving a pro... |
I have the following code in Scala as a solution to the problem:
Find the maximum number possible from the given Seq of Integers while keeping the individual numbers intact
e.g.
Seq(2,5,9,4) should result in 9542
Seq(4, 98, 10, 110, 91) should result in 9891411010
Note that in case of numbers with more than one dig... |
import random
student_teacher = input("are you a student or teacher")
if student_teacher == "student":
group = input("what class are you in")
if group == "1":
name = input("What is your name") #Asks the user to enter their name
print("Hello",name) #Prints a wlcome message to the user
sco... |
This code shows a title with an image and subtitle:
What improvements can I make in this code and is there a better of doing this?
package Components.CustomLabel;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
/**
*
* @a... |
Using file stream object, write a program to read an external text file ("myCourse.txt") which contains all the course name and numbers you are taking this semester, and to generate an analysis (total number of courses) into an external file ("myCourseSummay.txt").
This is a past question my teacher has been hinting... |
This is my solution of string calulator kata in scala(i'm new of tdd).
I'd like a general review of this.
String Calculator
Create a simple String calculator with a method int Add(string
numbers) The method can take 0, 1 or 2 numbers, and will return their
sum (for an empty string it will return 0) for example “” ... |
I have this small Java program for computing particurly large Fibonacci numbers (10000th Fibonacci number is computed in about 220 milliseconds). The key idea here is to use lists of digits, which is exactly what is done in java.math.BigInteger, yet I wanted to implement a simple digit list addition on my own.
import j... |
I am a relatively new programmer and am currently working on something with the egit GitHub client library which requires me to iterate over a bunch of values and if a condition is met, add a bunch of stuff to a HashMap then add it to a List.
Example:
List<Map<String, Object>> files = new ArrayList<>();
for (TreeEntry... |
The query below is quite slow (taking about half a second). Any obvious things I could improve?
The PRICES table has about 21 million rows and 30 columns while CONTRACTS has 130 k rows and 10 columns.
SELECT
CONTRACTS.EXT_ID,
PRICES.REFERENCE_DATE,
PRICES.PRICE_DATE,
CONTRACTS.PERIOD,
PRICES.TIME_TO_MATURITY,
PRI... |
I have completed a FreeCodeCamp exercise to create a tomato timer and chosen to do so with vanilla Javascript. Although it works, I don't like in how many places I am checking against two state variables onBreak and isPaused in many areas of the application.
(function() {
"use strict";
// Initialisation
... |
I've read that it is good to separate model from DB mapper (entity manager) (but at the end, it is perhaps personal - just a matter of opinion). Anyway, if I understood correctly, I should not have data models with DB connections, I should not have any methods with SQL (CRUD) in a class, right?
I will give you how my c... |
See the next iteration.
I have that method for computing Fibonacci numbers \$F_n\$ (\$n = 0, 1, 2, \dots)\$, that relies on computing
$$
A =
\begin{pmatrix}
1 & 1 \\
1 & 0
\end{pmatrix}^n.
$$
The solution is then read from \$A_{1,2}\$. Now I can easily compute, for instance, \$F_{100000}\$.
However, in this code snipp... |
I'm working on a class project for my intro to Java class. My background is in accounting/finance so I decided to make this simple calculator that helps the user decide what they can afford and how much they can save on interest expense over the loan term. I'm just looking for general feedback on code structure and tip... |
below I have coded a simple configuration manager that loads config elements from a file straight into a dictionary, and also has a function for getting an element by its key in the dictionary. I just wondered if there is anything I can do to improve this..
using log4net;
using System;
using System.Collections.Generic;... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.