instruction stringlengths 71 71.9k |
|---|
I have a list of lists of numbers. The numbers are in sequential order, ranging from 0 to n and each number only appears once. I want to loop over all the numbers in the list of lists and return the index of the list containing that number.
list_of_lists = [[2,3,4,5,6],[0,1,7]]
desired_output = [1,1,0,0,0,0,0,1]
I ca... |
Recently, during the interview, I was asked to implement basic arithmetic operations with common fractions using TDD. The task is fairly simple, but I was nervous so I did not do too well. :) Later on I decided to give it another try in more... comfortable environment. Here is what I came up with.
Tests:
[TestFixture]
... |
This accepts values from a user that needs to show up in a intervals of some number. In this case, we will say intervals of 5.
Is there a better way to do this?
public static int RoundTo(this int value, int roundTo)
{
var midPoint = roundTo / 2.0;
var remainder = value % roundTo;
var result = remainder < mi... |
I'm writing some code that helps me deal with units better, by having a user defined type for things like Metres, Centimetres and Millimetres. Here is the class declaration for Metres:
template <typename StorageType>
class Metres : public Unit<StorageType>
{
public:
static Metres fromMetres (StorageType metres) noe... |
Overall, I'm working on a simulator for a modified DnD 3.5 system. Right now, I'm trying to write an enum class that handles the Classes/Professions, and am currently trying to handle the profession modifiers for saving throws.
My issue is that everything is extremely boiler-plate, and I can't figure out a better way o... |
I have created a script that handles the responsive liabilities of my HTML menu. The menu will have a variable amount of <li class="menu-item">, resulting in a variable total width. I have 3 functions.
This function is responsible for looping through each li element and calculating the greatest width of the set of elem... |
The demons had captured the princess (P) and imprisoned her in the
bottom-right corner of a dungeon. The dungeon consists of M x N rooms
laid out in a 2D grid. Our valiant knight (K) was initially positioned
in the top-left room and must fight his way through the dungeon to
rescue the princess.
The knight has ... |
I am fairly new to C++, and to have a break from all that Java programming, I decided to do something in C++, which is sorting. The four sorting algorithms are:
Bubble Sort
Insertion Sort
Quick Sort
Merge Sort
Code:
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <iterator>
#include <chrono>
#define... |
This is now my new code implementing the recommendations from my previous question.
import os
import time
import mysql.connector
import MySQLdb
import ConfigParser
import base64
import logging
from logging.handlers import TimedRotatingFileHandler
import sys
import ast
import smtplib
from sendmail import send_mail
"""... |
Based on the previous question, I have utilized most of the answers.
The code is now fully compatible with the STL by implementing forward iterators to store and retrieve values.
Using raw pointers instead of smart pointers
The code is working as expected. I would like to know if my implementation is correct and ho... |
I have been worked on creating a chat tool similar to vk.com. Right now I have done a simple chat which requires only authentication via a PHP website and everyone can chat with each other. I used the NodeSession PHP class to access the PHP session in the node.js application.
To implement the application I used Yii1, n... |
I'm a C++ beginner and I was told to make a program to arrange three integers from least to greatest. How did I do?
#include <iostream>
using namespace std;
int main()
{
int x = 0;
int y = 0;
int z = 0;
int first = 0;
int second = 0;
int third = 0;
cout<<"Enter three integers to be arrange... |
The monkey-banana problem: There many variations to this problem, but the basic premise is that a monkey is in a room with a banana and
a chair, and the monkey cannot reach the banana until he moves the
chair close to the banana (so as to reach it), then climbs the chair
and gets the banana.
(Note : Often times,... |
Given K descriptions for bus line paths that exists to lead students between N campuses. What is the minimum cost that a student will have to goes from campus 1 to campus N ?
The itinerary of each path L is a sequence of |L|( ≥ 2 ) campuses {C1, C2, …, CL}, and each line has only one bus, which passes by all campuses ... |
I want to import a CSV file and do some operation on it.
The following is the code I'm using and it is working fine:
return function (req, res) {
var rl = require('readline').createInterface({
input: fs.createReadStream(myFile.csv)
});
var lineNumber = 1;
rl.on('line', function (line) {
... |
For the request object in my PHP application, I need to dissect the URL and assign its components to class attributes (module, controller, method and the rest are parameters). Currently, I'm doing it like the following but that looks ugly to me. Are there any better ways?
$urlComponents = explode('/', $requestUrl);
if... |
I'm looking for a general peer review on already working code. Just the overall structure and of course any gotchas like DRYness or logic issues.
var AccountExistView = Backbone.View.extend({
Name: 'AccountExistView',
el: $('#ue1_box'),
E: {
ue1_box: '#ue1_box',
// labels
u... |
This is my first step into Fortran. The program aims to provide a simple way of calculating numbers. Just looking for improvements in general.
program Calc
real :: a, b, additionAnswer, subtractionAnswer, multiplicationAnswer, divisionAnswer
print *, "George Gibson's Calc"
print *, "Type the first number: "... |
As part of a larger project I've created recently a simple CssBuilder and CssParser. It's composed of three classes and can parse/build inline and block CSS. Its main purpose was to render CSS for inline styles for email formatting (which is the rest of the project (maybe another time)). I also tried to design a fluent... |
From this hackerrank:
Problem Statement
The Head Librarian at a library wants you to make a program that
calculates the fine for returning the book after the return date. You
are given the actual and the expected return dates. Calculate the fine
as follows:
If the book is returned on or before the expected retu... |
I have a code to check if one shape (circle or square) envelops another. I have used this code. It gives true if the this object envelops the passed shape. Can anyone suggest me an improvement or better alternate method?
public boolean envelops(Shape s) {
boolean flag = true;
double distance = 0.0;
if(s instanceof Squ... |
Essentially I have a server that will be listening for sockets in other programs seeking a connection:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <sys/wait.h>
#include <signal.h>
#include <s... |
My input is basically a .png image from the img/ directory (I figured out that I should parse it, because there is an exploit possible at the moment) and a color which I want to be applied to the image.
The RGB color of every pixel from the image and my input RGB color are being converted to HSL, the H value from my in... |
Given a natural number \$n\$ (\$1 \le n \le 500000\$), please output the
summation of all its proper divisors.
Definition: A proper divisor of a natural number is the divisor that is strictly less than the number.
e.g. number 20 has 5 proper divisors: 1, 2, 4, 5, 10, and the divisor
summation is: 1 + 2 + 4 + 5 + 1... |
I'm making a prime number scanning algorithm in Java. It uses the concept of the Sieve of Eratosthenes to efficiently find the prime numbers.
It works well and can calculate all the prime numbers under 1,000,000 in less than a second on my laptop, but I was wondering how the algorithm could be further improved.
public ... |
This is a simple non-fair semaphore implementation using Java atomic objects. It currently performs a little over twice as fast as java.util.concurrent.Semaphore on my simple test.
The busy-wait loop in acquire() calls the Runnable specified during construction, so that users can provide their own custom back-off strat... |
I'm using Angular Smart Tables with data that might become a huge set of documents and rows. So rather than client side processing of the data for pagination, I borrowing code from two Mongoose.js plugins, put together a plugin to do server side processing for pagination with Angular Smart Tables. The plugins I used ar... |
I have an AngularJS function that is used to determine which $scope associative array variable is to have data pushed into it. I would love to be able to remove the switch case entirely if possible but haven't been able to envision a way to do that! My overall goal is to both improve performance, but more importantly r... |
I've been working on a implementation of specialty tree structure called a BK-Tree (more here and here). Basically, it's a tree that allows relatively efficient querying for items within a specific edit-distance (in my case, Hamming distance).
Anyways, it works, but currently with a tree of ~8 million items, a single q... |
I have a large numpy array of shape (n,m). I need to extract one element from each row, and I have another array of shape (n,) that gives the column index of the element I need. The following code does this, but it requires an explicit loop (in the form of a list comprehension.):
import numpy as np
arr = np.array(rang... |
I built an app where a user has a recipe box with recipes in it - for the db, there is a user and recipe model, user has "recipeBox" property. The recipebox is an array of objects like so:
User model....
User.recipeBox = {
["id1", "done": false],
["id1", "done": true],
}
The done property is for a checkbox on the fro... |
See the previous and initial iteration.
I have incorporated almost all the suggestions by Peter Taylor:
The actual method returns a BigInteger instead of String.
The actual method can deal with Fibonacci numbers with negative indices, so there is no any need to throw IllegalArgumentException.
The only base case that i... |
I'm solving this in perl:
https://github.com/kennyledet/Algorithm-Implementations/tree/master/100_Doors_Problem
Puzzle:
There are 100 doors in a long hallway. They are all closed. The first time you walk by each door, you open it. The second time around, you close every second door (since they are all opened). On th... |
Solving a 4Clojure problem, I got this answer to compress a sequence (problem 30):
#(map first (partition-by identity %))
What would be the best approach to have this work with plain numbers too?
My solution was this:
(defmulti comp class)
(defmethod comp java.lang.Long [x] x)
(defmethod comp :default [x] (map first (... |
I've been learning Processing for the last week or two, and I've made a couple of little 'desktop toy' type apps like this one that I'm quite pleased with. However, it just occurred to me today to look at the activity monitor while my app was running, and I was unpleasantly surprised – nobody wants a desktop toy that's... |
I have made the bold claim that a longstanding problem in Rebol is "now solved"...that of "definitional returns".
But of course, such claims need some peer review, and there's always some new trick to learn or improvement to make. So I thought I'd paste some code here. Even though it doesn't tell the full story of w... |
I don't have a strong mathematics/Matlab background. I would like to convert this Black level correction function from Matlab to C++. Please comment about on the code style and correctness of my equation.
Matlab
function output = calculateBlackLevel(blStruct, AG, ET)
blLut = zeros(length(blStruct), size(blStruct... |
I'm working on a small application that uses a WebService to get meta-data about television episodes. What I'd like to do is start building out a local cache of the series so that I can reduce the number of calls to the service. Data being stale is not a concern at all for this case. I've chosen to use an XML file t... |
I am developing a service where the user need to sign the seller agreement with Mobile BankID (Swedish e-sign service). To make this work I need to make SOAP request to get the progress status of the signing request in Mobile BankID.
Is this code understandable? How can I make it more clean?
def collect_request(transac... |
I have tried to implement the DFS algorithm to find all the back-edges in a graph that lead to a cycle in the graph:
public class CycleDetection {
private final Deque<Node> stack;
private final Graph<Node> graph;
private final Set<Node> visited;
public CycleDetection(Graph<Node> graph) {
super(... |
I was bored, so I wrote something that could turn .wav files in to .bmps:
#include <stdio.h>
char bmp[12000029]; // Need 12000028 bits, 1 pixel is 3
// bits and table is 28 (1500^2 * 3 + 28)
int main() {
bmp[0] = 0x42; // Bitmap signature
bmp[1] = 0x4D; // 'BM'
bmp[2] = 0x1C; //
... |
This is my final attempt of making an efficient ResourceManager class, which takes care of allocating OpenGL objects (like Shader, Textures, Meshes, ...). It stores each resource in a unique_ptr and then distributes const pointers of that type, which I call "Observant pointers." They cannot be deleted because resource ... |
I'm attempting to make a builder pattern that makes sense and is practical for storing user data in a flexible way in a document database. The DB I chose is MongoDB, and I'm using its Java API throughout. I plan on replicating this kind of pattern once I have something that is decent.
This works, but feels a bit clunk... |
The Jaccard distance between two sets is the size of their intersection divided by the size of their union. For example, the distance between {1, 2, 3} and {2, 3, 4} is 2 ({2,3}) / 4 ({1,2,3,4}) = 0.5.
The Jaccard distance can be used for string similarity by slicing a string into word or character n-grams. For exampl... |
This is a follow up question to my previous question. I am trying to design a thread safe parameters class with only readable getters. Idea is it should be possible to initialize this class once with some parameters - and throughout app I should be able to query values. Deinitialization should also be possible.
Please ... |
I'm currently doing a project, requiring me to implement a CircularQueue data structure in C++:
template<typename Type> class CircularQueue {
template<typename Type> struct CQNode {
Type head;
CQNode* tail;
CQNode() {
this->head = NULL;
this->tail = NULL;
}
CQNode(Type head, CQNod... |
I have written a simple system to load plugins from files in Python 2.7, and I'd like to see if any of it can be improved upon.
vedo.py
from __future__ import absolute_import
import os.path
import inspect
from vedo.event_emitter import EventEmitter
from vedo import VedoPlugin
def _get_module_name(directory, filenam... |
I am trying to learn functional programming in JavaScript, and saw a little task on Twitter that I wanted to have a go at:
var durations = ["12:38", "6:36", "9:03", "8:34", "5:02", "6:54", "13:22", "4:41", "8:36", "21:58", "3:06", "10:46", "10:13", "12:54",
"14:00", "11:03", "16:03", "10:52", "24:53", "10:03", "11:49"... |
I have modelled the task of super market pricing as per the below task.
http://codekata.com/kata/kata01-supermarket-pricing/
Please review my code and suggest any improvements.
class Product
{
String Name; //Name of the product
int unit_price;
UnitType unit_type;
boolean groupOffer; //Is this produ... |
The user has two 2D input arrays A and B, and a given matrix S. He wants to apply a
complicated formula to these arrays row-wise to get C. Something like: $$C_i = f(S, A_i, B_i)$$
where f is some complicated function, implemented by the user. That is, the user wants to supply his complicated formula in terms of the ro... |
I would like to be reviewed on efficiency, style, and obviously if there is a bug I would like to know.
def findsum(a, n):
''' Find whether a consecutive array slice sums up to n '''
for i in range(len(a)):
j = i + 1
while j <= len(a):
if sum(a[i:j]) == n:
return True
j += 1
return Fal... |
I wanted to write a JavaScript function that checked for balanced braces. I'd be grateful for any feedback on correctness and style.
var invert = {
'}': '{',
']': '[',
')': '(',
};
/**
* Returns `true` if braces are balanced.
* `false` otherwise.
* Usage: `isBalanced('{{[(')`
*/
function isBalanced(st... |
My script pushes zeros to end of an int array. I'd like to be reviewed on efficiency, style, and obviously if there is a bug I would like to know.
def nonzero(a):
''' given an array of ints, push all zeros to the end '''
zeros = [0 for i in range(a.count(0))]
x = [ i for i in a if i != 0]
x.extend(zeros)
retu... |
Find 3 elements that sum to zero in an int array.. I would like to be reviewed on efficiency, style, and obviously if there is a bug I would like to know.
def sum_to_zero(a):
''' given an array of ints, find 3 elements that sum to 0 '''
for i in a:
for j in a[1:]:
for k in a[2:]:
if i + j + k ==... |
I intentionally avoided Python tools which would make this even more trivial. I would like to be reviewed on efficiency, style, and obviously if there is a bug I would like to know.
def unique_char(s):
''' Find first non-repeated char in a string '''
myDict = {}
first = len(s)
for c in s:
if c in myDict.ke... |
I wrote this program, and it does what it asks, but it's so big and ugly. What can I change?
Some examples:
a b c --->
5 1 12 a is between b and c
5 12 1 a is between c and b
5 5 2 there is no gap
This was in an example of a test that is supposed to be small, so that's why I'm asking if there is anoth... |
Recently, I submitted a project that simulates a barbershop-style problem; the task was to create a Hotel that contained guests, front-desk employees, and bellhops. Each of these were to be implemented with their respective Semaphores, with mutual exclusion being kept to a minimum if possible.
My code works as expected... |
I'm trying to figure out how to organize interfaces in my game to make future development easier, by making my code more modular.
Notice that my Rook class implements the IPlayer interface, which will move it left and right, but not up and down (I had to add that in seperate methods). My question is, should I make an ... |
Please let me know how I can make it better, especially with avoiding repetition without the need to replace the user guesses.
import java.util.Scanner;
public class Lottery {
static int guess[] = new int[3],actual[]= new int[3];
private static void aquireGuess()
{
Scanner keyboard = new Scanner(S... |
I'm fairly new to Clojure and looking to improve my use of the proper idioms, and make my code more readable. Here's the problem:
Read from standard input and produce the count of each word to standard output, sorted by word, with a single space between the word and the count. Sort the output by word. Words are A-Z on... |
I wrote this code a while back and I have recently been rewriting most of my code. I just to know if these methods can be improved. The ones that pop out to me are listed below; others don't matter as much.
Methods that need improving:
FilterInjectionChars
IsValidAlphaNumeric
FilterFigure
namespace Apple.Application... |
From what I've seen in other posts, if I actually know the unwanted characters, then I can do string.replace(). But in my case, any characters can appear in my input string, and I only want to keep the characters that I want (without messing up the order of course).
private string RemoveUnwantedChar(string input)
{
... |
I'm running the following code on quite large data frames. I've rewritten it for the iris dataset to make it reproducable.
I'm quite unexperienced with the apply functions and I find them a pain in the bum to apply them.
Is there any ways to drastically improve the performance of this process?
lmfit <- lm(iris$Petal.W... |
Currently, when I'm wanting to print a value for my class I do the following...
<%= @person.team.name if @person.team.present? %>
This seems really redundant to me. I've also have done...
<%= @person.team.name_display %>
where I've created a function for each attribute to kind of hide the first case. It seems a lit... |
I currently have this code to read lines from a file
def getLinesFromFile(filename):
content = []
# with open(filename, "r+") as file:
# for line in file:
# line = line.rstrip()
# if line:
# content.append(line)
file = None
try:
file = open(filename, "r+... |
Awhile ago I posted a Translator app that I have been in the process of making. I edited some features in it and I've decided to post it again.
My questions:
Is there anything I should add to this?
Is there any better (more easily readable) syntax for what I'm trying to do?
Say I wanted to make a GUI for this app. Wha... |
I'm new to Python/Programming and wrote this simple "Day of the week/Holiday finder" script. Ideally I'd use something so I can have a little widget on my desktop, but right now I'm looking for any and all suggestions to improve my code?
I'm importing this holiday module
import datetime
import holidays
today = datetim... |
This is a follow-up to this question.
Using his ExactCover class, I slightly modified Garth Rees' Alberi class to cope with regionless schemes and forced void cells:
"""Solver for an Alberi puzzle using exact cover
"""
from collections import Iterator
from itertools import product
from ExactCoverExt import ExactCover
... |
Is there a better way to optimize this code? It started with \$O(n^2)\$ (nested loops) then \$O(n)\$ (with index).
public static String getRelativePath(String from, String to) {
String relative = "";
String regexPath = "/";
String regexLow = "..";
List<String> toList = Arrays.asList(to.split(regexPath)... |
I have a method in a Python app to write a list of records to a CSV file. Each record is a "football player", which is really just a dictionary. But one of the dictionary items contains a list of weekly scores. I want to write out to CSV a record for each player, and then flatten the list of scores and write that ou... |
Problem description:
You have two eggs, and need to find the maximum floor of a 100-floor building from which you can drop the eggs without them breaking. Do this with as few attempts as possible.
NB! You are passed the level of where it breaks, n, and an egg is considered broken when your compares and finds test floo... |
I was recently given an interview and was asked to write my own lock implementation using atomics, but not necessary reentrant.
I didn't answer the question, but at home, I wrote this code. Please asses my implementation and suggest better solutions.
public class MyLock {
AtomicBoolean locked = new AtomicBoolean(f... |
This is a simple wrapper class for a lambda expression, that stores one as Expression and hands it back out either as Expression, or compiled as Func. This is useful because while Linq-to-Objects requires a Func, other technologies such as Entity Framework require an Expression (so that the expression tree can be proje... |
I've been teaching myself C for the last few months. As a learning exercise, I set out to write an ncurses implementation of the classic card game Uno, mostly because it was was one of the simpler card games I could think of.
Since my emphasis in writing this was primarily learning concepts and algorithms, the interfa... |
I've written some code to solve the longest palindromic subsequence problem.
def memoize(f):
""" Function decorator used to cache results """
d = dict()
def inner(*args):
if args not in d:
d[args] = f(*args)
return d[args]
return inner
def max_palindrome(s):
""" Returns ... |
The following code gets video renditions from Brightcove using the media API. It then generates an ordered source list for the JW Player and selects the default rendition based on a pre-set bitrate.
function buildSourcesFromBrighcoveID(brightcoveID, onComplete) {
var sources = [];
var brightcoveAPI = 'http://ap... |
I recently watched a video course on groovy and started working on some of the Project euler problems to flex my groovy* muscle.
(This is problem #8)
The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832.
Find the thirteen adjacent digits in the 1000-digit number tha... |
For an exercise, I've written a function that, given an array of objects and a key (2nd argument), returns a new array of objects that contain all properties from a key. How'd I do?
function where(collection, source) {
var arr = [];
var keys = Object.keys(source);
var countMatchingProps = 0;
var currentProp... |
This relates to Round to specified int but I'm separating these methods out since they're technically different.
Is there a method that already performs a custom floor and ceiling to a specified integer?
// If the interval is 5, 9 --> 5.
public static int FloorTo(this int value, int interval)
{
var remainder = valu... |
I'm displaying multiple queries and if statements. In the if statement, it increments notice_category_id by 1 each time a category is created, but when I code the update/delete/edit (or if truncated), sections won't rowCount() increment the row and make duplicates. I'm just wondering if I should change the way the the ... |
Cardshifter is an online trading card game, made by a gang of Code Review community members. Cards can have a bunch of different, and sometimes complex effects, and descriptions for these are automatically generated if no custom one is given.
EIGHT IMMORTALS:
Choose 1 at random: Summon 1 Life Tool to your Battlefiel... |
I can see a possible performance optimization with declaring 2 arrays and iterating the $fake_widgets only once, but how else can I make the following conditional string building more elegant in Ruby?
pending_coloring = $fake_widgets.select do |widget|
widget[:status] == 'awaiting_coloring' && widget[:owner_color] =... |
I've created my first Android drawable, a hourglass shaped image, and I'm curious what can be improved with it. It seems weird having to use 4 paths, but I couldn't get it to work any other way.
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:wid... |
Curious what people think about this implementation of Conway's Game of Life in Haskell.
{-# LANGUAGE QuasiQuotes #-}
module Test.Conway (
conwayCalculateAge,
conwayStep,
conwayMakeRandom,
conwayMakeRandomIO,
conwayMakeEmpty
) where
import Data.Array.Repa
import Data.Array.Repa.Stencil... |
I am writing code that creates a hash for a store that has an item, price, and sku. The hash is inserted into an array. I also create another hash based on the sku that holds the amount of inventory for that item. I am new to Ruby and am looking for ways to improve my code.
class SimStore
def item_info
... |
I heard goto is bad, so I ask someone in this site if my code is better using goto or other alternative
public FormMain()
{
// start of the apps
Start:
// show login form
FormLogin login = new FormLogin();
DialogResult dr = login.ShowDialog();
// cancel form loading if ... |
I have been programming for a couple months now and really wanted to make my own game, so I chose battle ship due to is simplicity (I learned out how wrong I was). I know one thing I am going to hear about is that it isn't portable due to the fact I am using the windows library. All I have to say is I tried finding oth... |
This computes the integer square root at compile time for any \$0 \le N \le L\$ where \$L\$ is the largest integral representation of template parameter T.
This was motivated by the fact that many of the algorithms I found were not able to handle large values of \$N\$. I also just wanted to practice template meta-progr... |
This code creates a singleton event dispatcher. It's called like this:
eventDispatcher = Event()
eventDispatcher.on("event", handler)
eventDispatcher.trigger("event", 5)
I'm wondering if this is "the python way," or if it could be improved? Especially the class, I'm not sure about creating a new object for every use... |
Scenario: I have a main thread which spawns few child threads to do some independent tasks. After each child thread finishes their tasks, the main thread proceeds. The code I have written is working in most of the time. However, in case one of child thread gets blocked, the main thread has to wait for ever. As it is no... |
My tooltip works fine, but I need to simplify this code.
var genderSelect = {
getGenderSelect: function () {
if(this.val('Girl')){
$(this).find('#girl-character').show();
$(this).find('#boy-character').hide();
}else if(this.val('Boy')){
$(this).find('#boy-character').show();
$(this).f... |
The implementation of the algorithm which adds two number in string form with arithmetic rules.
var assert = require('assert');
var strAdd = function(lnum, rnum) {
lnum = lnum.split('').reverse();
rnum = rnum.split('').reverse();
var len = Math.max(lnum.length, rnum.length),
acc = 0,
res = [];
for(... |
I have created a ViewModel for a Product Edit page because it has specific related entities I need to load - the class currently looks like this:
public class ProductEditView
{
public ProductEditView(Product product)
{
this.ID = product.ID;
this.Code = product.Code;
this.ProductLanguage ... |
The new EcmaScript standard, ES6, contains specifications for Map and Set built-in classes. Each of these collections treats an object-valued key as opaque and unique, e.g.:
var foo = new Set();
foo.add({bar: "baz"}).has({bar: "baz"}) // == false
However, there are cases in which one might want to treat similar objec... |
I've recently finished writing a "simple-as-possible" LDA code in Python.
The theory from which I've developed my code can be found in the book Computer Vision by Simon Prince, free (courtesy of Simon Prince) pdf can be found on his website: http://computervisionmodels.com/ - Chapter 20 talks about LDA.
Applied to comp... |
I have a LINQ query that I am having trouble optimizing and takes about 5.5 seconds to run. I am using a view called StaffingResourceData and a table called StaffingForecasts.
Each StaffingResource has a ResourceId, a Division, and a Type. A StaffingForecast has a ResourceId, Project, Date (represents a Monday of a we... |
This implementation uses ECMA6 syntax and babel as transpiler. You can use this code to add integers which are bigger than Number.MAX_SAFE_INTEGER.
var _ = require('underscore'),
assert = require('assert');
var strAdd = function(lnum, rnum) {
var {rem, res} = _.chain(
_.zip(
lnum.split('').reverse(),
... |
This question presents two rather small Java programs: the first one is a simple client that reads text from command line and sends it to the server (TextSender.java); the server does nothing more but echoes the received text on the command line (TextReceiver.java)
TextSender.java:
import java.io.IOException;
import ja... |
My goal is to find the largest connected "cell" of 1's in a matrix.
My approach has been to search the surrounding area of a cell that is not on a border and then if it hasn't been visited, and has a value of 1, increment the group. I am absolutely sure that there are better, more recursive solutions out there, but I ... |
I want to know if there is any other better way to write this algorithm. What other data structures could be used to make it more simple and effective?
public class BubbleSort {
public static void bubbleSort(int array[]) {
int n = array.length;
int k;
for (int m = n; m >= 0;... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.