instruction stringlengths 71 95.1k |
|---|
So this original piece of code:
const imgUrls = {};
function onXhrLoad() {
const json = JSON.parse(this.response);
const photos = json.photos ? json.photos.photo : [json.photo];
for (const {id, url_o} of photos) {
imgUrls[id] = url_o;
}
}
The original code assumed that the biggest available url to an imag... |
Just started learning/relearning data structures for the semester exams. Most of the examples found online are too cluttered or bloated.
For myself, I implemented it from theory I learned.
It works.
I want to know if there are any mistake that I have done, anything that can be improved .. .
Thanks for your time :)
#i... |
The following code computes three different features over the same dataset. I'm not sure if the filter_by_day_segment function can be made tidy or there's a more efficient/short but still readable way of refactor my code.
library(dplyr)
filter_by_day_segment <- function(data, day_segment){
if(day_segment == "daily"... |
I have built a class which validates configuration data. Below is a very simplified version with only the code that's relevant to this question.
class configValidator
{
private $_errors = [];
public function validate()
{
$this->errorGenerator(1, 'fail');
if ($this->_errors) return $... |
So I'm creating a unity3D game with infinite terrain and it's going great! However, I'm struggling with a specific but important part of the 'infinite' terrain. Make the terrain actually infinite. I got it working but it's very slow and I've looked through the code and at the profiler that unity has built in and came t... |
The past week I have tinkered making a sound visualizer using Tkinter, Matplotlib, NumPy, PyAudio and using a thread to be able to play the sound and to display the plot at the same time.
I have been coding Python now for almost two years and I think the program expresses my knowledge as to date.
I would appreciate rev... |
The goal
I really enjoy the game Stardew Valley. One of the things that the game has are geodes. Much like real-world geodes, these geodes can be cracked open, and you can find some fun things inside.
Some relatively rare/valuable items can be found inside of them, so it can be beneficial to try and collect them to get... |
I have recently learnt SOLID patterns and started practicing them. I did follow all the guidelines but was thinking for a final review from experts if possible.
What is the code about ?
It encrypts any given string and outputs a hash.
Code
interface IHash
{
string Hash();
}
// Abstract class implements interface
p... |
I have some code which transforms a transformation on quaternions and works. But it is written pretty badly, does someone know how to write this better/shorter and does someone knows, if this entire transformation is a transformation 90 degrees on y in euler angles?
Edit: I get a quaternion (orix, oriy, oriz, oriw), th... |
Here is the description of the problem.
Write a simple interpreter which understands "+", "-", and "*" operations. Apply the operations in order using command/arg pairs starting with the initial value of value. If you encounter an unknown command, return -1.
Example:
interpret(1, ["+"], [1]) → 2
interpret(4, ["... |
This library provides methods for storing items into an inventory. the container is based on a grid as well as the items going into that container.
can you please review the code in any way?
public interface GridContainer {
public Collection<GeoPoint> getContainer();
public Collection<GridShape> getContent();... |
I'm not a professional Javascript developer and never worked within JS teams. I've made a small library, that is kind of a silly ReactJS clone, optimized for size and minimalism aesthetics, rather than performance. Terrible performance is by design, but I would like the code to be at least a little bit more readable.
M... |
I'm trying to design a better solution for img srcset with lazy load.
Below is the code from the component responsible for lazy load img,
maybe someone has a better way to achieve this effect.
Full github repo
import React, { useState, useEffect, useRef } from 'react';
const ImageLoader = ({ alt, height, id, width })... |
I have just finished learning basic-intermediate Python subjects and wanted to test myself. This word-guessing game is one of the first programs I have written.
import random
def pick_random_word():
word_list = ["python", "c", "java", "swift", "html", "css", "go", "ruby"]
random_word = random.choice(word_lis... |
I built an algorithm to estimate real-time temperature and humidity values based on daily values of the same variables. The algorithm works, however the speed with which it processes the information is too slow and this causes me problems when the data is of many years or decades.
I need to increase the processing sp... |
This code is about merging two or more images. Minimum images are two while maximum images loaded are four. So I will check how many images the user wants to merge. If the user chooses 2 and selects the merge type, two images will be checked for their height or width to resize then append them. I keep using the code fo... |
I have just finished learning basic-intermediate Python subjects and wanted to test myself. So here is the my basic Rock-Paper-Scissors game.
def play():
import random
player_score = 0
ai_score = 0
while True:
try:
user_choice = int(input("\nRock: 1"
... |
EquiLeader
A non-empty array A consisting of N integers is given.
The leader of this array is the value that occurs in more than half of
the elements of A.
An equi leader is an index S such that 0 ≤ S < N − 1 and two sequences
A[0], A[1], ..., A[S] and A[S + 1], A[S + 2], ..., A[N − 1] have
leaders of the sam... |
I have working VBA code in excel that changes a network folders permissions.
The code uses Wscript.Shell to run icacls commands but there are multiple instances of this command and each time it runs, it opens up a new shell window.
It would be interesting to see if there is a way of making the code more efficient by op... |
I implemented a sign in from different accounts on which different amounts of money lie. You must also specify what will be sold in the store. When you buy, you can put things in the basket, get them out of there, empty the basket. When you exit, the transaction will occur, and money will be withdrawn from your account... |
I wrote a Keylogger in Python who transfers the Key Strokes to an S3 storage. What do you think about the Code? I would add the file saving in an other place and make it more legible. Feel free to copy the code and use it for your own.
To run and compile it you need:
Python 3.7.5
boto3
pynput
pyinstaller
Greetings
""... |
I've been using Beanstaldk (not Amazon's one) for years and loved the possibility to handle delays and priorities in the tasks, but I recently had to filters the tasks for specific reasons, and Beanstalk doesn't allow that easily.
So, after searching a bit, I decided to use Mongo as it seems to be pretty fast, and I wr... |
I've written the following Octave function which is designed to be repetively called in a Bayesian optimisation routine and which outputs a value J, the Akaike Information Criteria for the Logistic regression model being tested, given the data
function J = rvfl_training_of_cyclic_embedding ( x )
global sample_features ... |
About a year ago, I wrote a Python script that enumerates all the files in a directory, partitions them based on a couple of criteria (file size, a custom byte-signature of the file, hash, ...) and finally creates hardlinks between identical files. The partitioning is intended to minimise the number of full-file compar... |
I have made custom basic MVC using index-php. I have a very long add function which does alot of things. sanitisation, validating, more checking data etc.. finally input new records. Sometimes the add can be huge so what i have done is create a background task which does some of this at a later time run independently f... |
I was tasked with solving this particular problem:
A water pool which can hold a total of 800 liters of water has 3
pipes. 2 of them pour water in, the third one pours water out. 1st
pipe pours 100 liters in, 2nd pipe pours 80 liters in and the third
one pours 110 liters out. The pool must keep its volume betwee... |
I have a code for a short Python 2 Pig Latin translator. Is it a good code, or should it be revised?
pyg = 'ay'
original = raw_input('Enter a word:')
# allows user input ^
if len(original) > 0 and original.isalpha():
word = original.lower()
first = word[0]
new_word = word + first + pyg
new_word = new_word[1:len(new_wo... |
I was doing Optimal Utilization code from leetcode
Question Link: https://leetcode.com/discuss/interview-question/373202
Question:
Given 2 lists a and b. Each element is a pair of integers where the first integer represents the unique id and the second integer represents a value. Your task is to find an element from ... |
Made after seeing A Simple Word Guessing Game. Any code critique is welcome!
import urllib.request as Web
import random
import string
def get_words():
url = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain"
req = Web.Request(url)
res = Web.urlopen(req).read().splitlines()
... |
I made this to record the time I spend practicing Python. I'll eventually add in functionality to visualize the data. I'd appreciate any feedback that will help me improve.
# timer.py - A timer to track time spent practicing python
from datetime import timedelta
from datetime import datetime as Datetime
# used json b/... |
Context
The following script is a quick implementation of the gambler's ruin problem. For each given upper bound on the number of rounds in a game max_iter, simulate several games (trials) in parallel and summarize statistics.
Question
Is there a more efficient/neater way to parallelize? For example, the main method si... |
WiKi and GitHub.
Sudoku rules are being checked with the following tests:
[TestMethod]
public void Be_Valid()
{
var data = new int?[,]
{
{ 5, 3, null },
{ 6, null, null },
{ null, 9, 8 }
};
var board = new Board(data);
Assert.IsTru... |
LINQ/FP style:
Assert.IsTrue(new[] {1,2,3}.AnyPairSum(4));
Where:
static class LinqDemo
{
public static bool AnyPairSum(this IEnumerable<int> source, int sum)
{
var a = source.OrderBy(i => i).ToArray();
return scan(0, a.Length - 1);
bool scan(int l, int r) =>
l >= r ? false ... |
I've made an POC about a bitmask implementation in order to replace a huge if/else statement.
Those statements are about strings and I have almost 15 /20 string to test. Depends on values the if/else statement was about 1500 lines of code.
After refactoring I was able to have only 20 objects and a map with all my callb... |
I wrote this map function, that should loop a very nested array of objects and find and exchange an item. To make my life easier, I also pass a path array: [1, 4, 7, 23] that shows in which id-s my nesting happens. The last id is the item I need to swap. Here is my function:
() => {
const { id, parentPath, question ... |
# Stack Overflow
'''
Goal: pull back all tables in a database where column name 'Audit Report' == 'complete'
Why is this a script: There are over 1000 tables in the database with the same structure
this script will automate checking which reports have a 'complete'
unde... |
I have just finished learning basic-intermediate Python subjects and wanted to test myself. This Battleship game is the third game i have written.
import random
def create_random_ship():
return random.randint(0, 5), random.randint(0, 5)
def play_again():
try_again = input("Wanna play again? <Y>es or <N>o? >... |
I have two functions, one that returns two values min and a max and another function that serves as a guard. However I would like to
remove the logic of the if/else inside the invalidPriceRangeException function.
be able to know that priceRange returns an a min and a max without having to know that the first number i... |
I'm building an image filtering application, and I'm new to the Java frameworks that I need to do so. Right now, I can apply a simple 3x3 kernel blur to my thing by overwriting the RGB values of the destination picture pixel by pixel using the RGB averages from the original photo. I'm trying to increase the speed at wh... |
This is my code for the Mars Rover Challenge, would be nice to get some opinions on it. More details about what the Mars Rover challenge is can be found here:
https://code.google.com/archive/p/marsrovertechchallenge/
The Mars Rover takes an IEnumerable<string> of instructions, the first element is the size of the surfa... |
Business Process: Data entry form allows HR employees to input data for new employees, update data for existing employees, or terminate employees. Three data storage sheets exist for existing employees: Basic information, personal information, and education information, and one exists for separated employee information... |
need to rewrite some code I already have. It insert columns where a 'Standard Deviation' column is missing. To do that it checks if the preceding column is a "variable" column, and if there already is a "Standard Deviation" column after it.
Right now I'm using a while loop that iterates through the columns checking df.... |
I was doing Favorite Genres code from leetcode
Question Link: https://leetcode.com/discuss/interview-question/373006
Question: Given a map Map> userSongs with user names as keys and a list of all the songs that the user has
listened to as values.
Also given a map Map> songGenres, with song genre
as keys and a li... |
I've written a function to create an HTML tree from JSON.
async function traverseTree (list, node) {
const li = document.createElement('li')
if (node.kids) {
const
ul = document.createElement('ul'),
span = document.createElement('span')
span.innerText = node.name
li.appendChild(span)
li.... |
Here I am trying to simplify my bootstrap name using dot notation, but I'm having lots of issues getting my nav to render different pages.
Am I setting my routes properly?
Am I setting the switch properly?
Am I setting the Link properly?
I found most of my information here. I tried bringing in a switch on the App.js ... |
I created this game inspired by this problem: https://www.codechef.com/ZCOPRAC/problems/ZCO14001
The problem needs you create a machine that can lift boxes and drop them in a new column. Then, when the problem asks you to, you have to print how many boxes are in every column.
I tried to improvise it and make it as a... |
I'm reading a file with the following data,
char peer0_3[] = { /* Packet 647 */
0x02, 0x00, 0x04, 0x00, 0x11, 0x01, 0x06, 0x1b,
0x04, 0x01, 0x31, 0x0a, 0x32, 0x30, 0x31, 0x39,
0x2d, 0x30, 0x36, 0x2d, 0x31, 0x30, 0x0a, 0x32,
0x30, 0x31, 0x39, 0x2d, 0x30, 0x36, 0x2d, 0x31,
0x30, 0x01, 0x30 };
with the following code... |
The purpose of this cluster of functions is to tail the log file and kill/restart processes from shell (the latter is not yet implemented).
import sys
import time
import datetime
import os
import re
def read_log(f):
"""
Basically tail -f
"""
logfile = open(f)
logfile.seek(0, os.SEEK_END)
while... |
The idea is to convert first 8 character from the C string to uint64_t or uint32_t, then to convert to Big Endian.
The value can be stored and compared with same values and result will be compatible with memcmp or strcmp.
The only exception is if both "strings" are 8 bytes long or 4 bytes long for uint32_t and are equa... |
I have written a C function to parse an IP address that should match the regular expression ^\d+.\d+.\d+.\d+ and nothing else.
Additionally all bytes are limited to 0-255.
I tried to catch all invalid inputs, but I am unsure if there are any edge cases I missed or if it could be simplified.
The function is intended to ... |
It is a simple Poker balance/bid tracker to automate calculations for players' scores.
It is a project I made to practice the concepts of lists and indices.
And thus heavily relies on indexing and list search.
I know I could have used dictionaries, but I chose not to get familiar with previously mentioned concepts.
I'm... |
I have an MVC application that uses Active Directory membership for user authentication.
After the user logs in, a FormsAuthenticatedTicket is created and encrypted. Then, in Application_PostAuthenticateRequest the ticket is decrypted and the deserialized user data is stored in a custom principal object.
My problem is ... |
I am making a program that scores a scrabble game and this is the basic version of it. Eventually I am going to add logic for double and triple words and letters but before I get too ahead of myself I would like to improve the basic code here.
All suggestions are welcome.
def main():
letter_val = {" ": 0, "a": 1, ... |
I created an area of shapes calculator. It's my first python script and I just wanted to get a few tips, thanks in advance!
#Area of selected polygons and polyhedrons calculator.
import sys
import math
on=0
print("This is an area (or surface area) calculator for selected 2D and 3D shapes, press 0 to start.")
start=inpu... |
I am trying to learn Rust and I feel like a dummy every step of the way.
I went through the tutorial on making lists in Rust. I am trying to apply the knowledge to implement a simple BST.
The code looks pretty horrible though. Any suggestions on how it can be improved?
pub struct Tree<T: Ord> {
root: Link<T>,
}
... |
I have a function that accepts a range as an input. It works fine when I supply the function with a range like a1:a5, but not when I use an entire column like a:a.
I could always loop over the whole column (ie. a:a) but that is so slow.
Here is a simple example.
Function r_sum(r1 As Range) As Long
For Each c In r1... |
Im trying to think of the most efficient way to structure an in memory leader board with the ability to read a specific rank quickly. Im talking about very micro optimisations as either way it will still be fast.
class Leaderboard
{
constructor()
{
this.leaderboard = [];
}
insert(name, score)
... |
I'm working on a method to rotate System.Enum values that have the [System.Flag] attribute set. I've tried to think of cases where there is no work to do (set to enumVar.ALL or enumVar.NONE where no rotation can occur, or when a request is made to rotate 0 positions).
The whole of it can be seen here.
For me, the bigg... |
This code extract data from generic mailbox mapped by MS Outlook
I failed at recursive iteration in subfolders, so it stays as iterative one.
Added ASCII encoding to deal with crazy national symbols in body/subjects.
My main target is to ensure scalablity and prevent it being slow (iteration over 100 generic mailboxes)... |
I wanted to understand how base64 encoding (and decoding) works so I implemented this tool in the spirit of "classic UNIX tools" (read from stdin, write to stdout).
I'd like to get general feedback on style and implementation (hoping I got it right). Also, since I'm doing bit manipulation, should I worry about endianne... |
I'm learning Rust and a few questions did arise during translation of my C++ code to Rust. There are comments in Rust code I'd like to be answered. Is there an idiomatic way to solve this task? The task was in simulating a random process - there are two chairs, which have different processing capacity and there is a fl... |
I am using react-flow-chart for a job project, but it doesn't implement zoom, and I would like to take the reigns and try applying it myself. I took a linear algebra class in college, but I am not very good at transformations. I could make my job a lot easier if I directly use CSS transforms and have it do the heavy li... |
I have just created an encryption program with a friend. I wanted to know if anyone here could give me back any feedback on it.
Here is how the program works:
Imagine you want to encrypt the word 'hi'.
Depending on the key generated with the program, the computer will choose between 2 strings of two letters randomly fo... |
I'm currently learning about Entity-Component-System architecture Data-Driven design as a way to counter bad OOP design and optimize data fetching as a CPU friendly operation.
I'm trying to write a simple ECS system that tries to follows these principals:
CPU friendly by storing entities/components in contiguous chunk... |
I'm working on a site where you can read about different songs, listen to them, rate them etc, same with their singer.
I've been thinking about how I could create a simple, yet perfectly working pagination script using PHP, and yesterday at night I came up with the code which you will see below.
So first this is the fi... |
vstrsepf is string parsing utility function born from the idea of using strsep and strtol with a sscanf-like interface.
This is an attempt to build a safer scanf for embedded system application.
Some key design choices:
Will destroy its input string (by adding '\0').
No dynamic memory allocation.
Reentry safe (RTOS a... |
I wrote a (very) simply Python3 password manager to familiarize myself with Sqlite3, and for fun. I am aware that there are already a variety of password managers out there, but I wanted something simple and secure(?) to replace the very insecure bashrc function that I use to generate random passwords and store them wi... |
This is a lightweight version of std::shared_ptr<T> called res_ptr<T>
This post is a continuation of:
A lightweight version of std::shared_ptr<T>
Revisited the code due to review from @TobySpeight and @MartinYork. Fixed errors and implemented full support for all types of data.
std::shared_ptr<T> stores a whole control... |
This is a follow-up review of Calculate the sum of interior angles of a polygon.
Using the helpful answers from the original post, I have integrated the suggestions which are in order from first to last:
Adding checks to scanf().
Using main(void) in place of main(...).
Passing char * directly to printf().
Made conditi... |
This challenge took me forever. I spent a lot of time messing with regular expressions, but couldn't get it to work. I ended up coming up with this abomination. If anybody wants to take the time I'm interested in simpler ways to accomplish this task. (I'm a brand new pythoner)
def is_stressful(subj):
"""
... |
As my applications rely on VT-100 emulation, I found that I had to do quite a few workarounds to determine the number of visible characters in a string with embedded VT-100 control codes. So that led to the design of this 73 byte snippet.
Function would be called as follows;
xor edx, edx ; ARG1 - DX = 0 ... |
I have a simple integer sorting problem at hand and to solve it, I am planning to write a variation of bubble sort. It seems to be working fine but I am not sure about it's complexity in big-O. What it could be ?
public class TempBubbleSort
{
static Integer[] myArray = {10,9,8,7,6,5,4,3,2,1};
static int counter = 0;... |
This game is made for JFrame. You can control using the arrows. The numbers in the cells are the degrees of the number 2. It is possible to change the initial position of the window, its size, and the number of rows-columns(they are equal) in the field. You can also change the width of the frames of the cells, indent b... |
I wrote a simple script to log HDD and CPU temps to a log file.
If those temperatures reach a threshold, it will shutdown the server. I also made the script make sure the log files don't get over a certain file size. Any ways to improve the code would be greatly appreciated, as I am a noob to programming.
#!/bin/bash... |
I'm learning C++, data structures and algorithms and I have implemented a (Doubly) Linked List class for practice.
Some STL functionalities are deliberately missing for now (e.g. some functions overloads, rbegin/rend/crbegin/crend, relational operators
and many others). I would like to know if my approach is correct be... |
The goal of the project is to automate sending the same e-mail to a list of people with the same text (except the salutation "Dear Name of Person") with an HTML signature and a PDF attachment.
For this purpose, I have:
An Excel list with Name, E-Mail, Subject and a "sent?" field (that has to be marked once the e-mail ... |
I have been developing multilanguage website based on Symfony4. Structure of one of the tables:
Field
Type
Null
Key
Default
Extra
id
int(11)
NO
PRI
NULL
auto_increment
title_en
varchar(255)
NO
NULL
title_fr
varchar(255)
NO
NULL
title_de
varchar(255)
NO
NULL
parent_id
int(11)
NO
NULL
What is ... |
This code inputs a weighted edgelist, positive and negative sentiment seed words, and a target word. The program computes the sum of the weights along shortest paths from the seed words to the target and from the target to the seed words, as it generates 9 output values.
The program is very slow. Running large edgeli... |
I've created a function in python to print some information through it. I'm trying to supply list of alphabets to the function along with the type those alphabets fall under.
When I execute the function, It checks whether the value of the type is None. If it is None, it executes the except block to fetch one.
I've trie... |
I have a short test to validate that all committed files in the repo are formatted. I'm new to go so not sure what the best wat to do it is.
The error handling, in particular, is rather gruesome as it takes up roughly half of the lines.
package pack
import (
"os"
"os/exec"
"path/filepath"
"testing"
)
... |
I want to use an std::array, but am operating on sufficiently large arrays that stack allocation is not reasonable (and fails using default stack size). I also needed a function that performed much like std::transform, but always in-place. The issue is that many of these transformations change the "type". All of these ... |
I would appreciate any review of the following script I recently posted on GitHub (gitcrypto). Most notably, I would be interested in a review of the cryptographic aspects (I am not an expert in this field):
Is there a way to break the encryption from the files in the "export" directory alone without knowing the passp... |
Here is an attempt to leverage Java's BigInteger class to implement the RSA algorithm, as well as md5 and sha512 hashing functions to generate keys for what I hope to be strong cryptography. My prayer is that some of my ideas are novel and not just wrong.
This is a test, this is only a test. 'Keys' are generated, the ... |
This is my Python 3.6+ version of the Hangman game, with graphics generated with print and .format. I've never written code professionally so I would like to know what must be changed to reflect good practice, efficiency, clarity of comments.
from random import randint
import os
WORDS = ["word", "object","radiant","wav... |
This is the 26th exercise I solved from Codility. It scores 100%. I think I improved a lot since I started with this lessons, around 2 months ago, but still every post I made had things to be improved. What do you think about this code?
Task description
A non-empty array A consisting of N integers is
given. A pai... |
I have this angular service that is working perfectly but I'm feeling that it isn't very readable.
How would you refactor it?
(Simple tips as "try this instead of that..." are very welcome. I'm looking for different approaches.)
import { Injectable } from '@angular/core';
import { concat } from 'rxjs';
import { map, co... |
I am learning Python, so pardon me if this is the very crude approach.
I am trying to generate a random string using alphanumeric characters.
Following is my code:
#Generating random 6 character string from list 'range'.
def code():
# List of characters [a-zA-Z0-9]
chars = ['a','b','c','d','e','f','g','h','i','... |
The Fizz Buzz challenge is well-known and should not need any explanations, right?
I recently got a bit bored and came up with a solution for Fizz Buzz using LINQ and even asynchronous code and a lot of extension methods. Actually, it's only Extension methods!
So, I thought, let's share it and have a review of my code!... |
Not long ago, I was asked about how many lines of code I have written in C++ and could not answer that question. For this reason and to become more familiar with Bash shell scripting, I wrote a small system to monitor the lines of code written in a specific subdirectory.
Currently, I count the lines of code at 5 second... |
I have a char tempBuffer which stores say my!string!hello!. After every ! is encountered that token is moved to a char codeBuffer and the rest of the characters are shifted to the begiinging of tempBuffer. So after my is moved to codeBuffer, tempBuffer contains string!hello!.
I have currently implemented it as follows... |
I'm just use the add_filter('the_content', function($content){}); for filtering anchor tags in a post.
Basically, I want filter anchor tags to appropriate format. I want to add custom attributes like rel="nofollow noopener" and target="_blank" if the anchor tag linked to external of my WordPress site.
Instead checking ... |
I build this silly app to get the commenters' information on some PR, mostly for learning how to use API's and for improving my JS dom skills.
Although it is working, it's mostly spaghetti code and very disorganized, so I am sure there is a lot of room for improvement.
I would like to get some feedback on how to better... |
I've the following code working on stackblitz editor as shown in this URL.
Right now I have only 2 tabs. Let's say if in future I have 20 tabs, I don't want to have 20 different this.initGrid(); for each tabs.Is it possible to create a separate file for first tab(something like firsttab.tsx) , the functionality is defi... |
I know there is this thing called "Eratosthenes" but that requires the allocation of a large array while I want to find (small) prime numbers fast, yet without needing too much memory. So I wrote PrimeTable.cs with this content:
using System;
using System.Collections.Generic;
using System.Linq;
namespace Primes
{
... |
I am trying to get all image urls which are valid and unique.To make sure i wont end up using the same image again i calculate hash of the image and store it in a text file and read the text file again.if there is any better way to do this, please let me know.Overall any speed optimisation would be really helpful, than... |
So, few months ago I did a HackerRank test for a company. The problem was to create a function which receive a list of names and returns a list of unique usernames. For example:
For the list of names = ['john', 'john', 'tom', 'john']
The function must return: = ['john', 'john1', 'tom', 'john2']
My code was:
def use... |
Now that I finally have time to look back at this code I wrote over a year ago. I need help with streamlining the code I have written. I had to write a significant amount of IF statements to get this to work, but im thinking using functions anbd maybe dictionaries would be a much more efficient way to go about this c... |
I've written a python script that solves a restricted variant of Subset Product by using integer factorization. The purpose of the script is for my empirical observations of the similarities between factorization and the NP-complete problem.
The code compares two sets (or lists) from the original input arr and the fact... |
So I was doing some challenges on codewars.com and came across the following challenge (I managed to close the browser so could not submit my answer and therefore could not see the best possible solutions).
Given an array of at least 3 integers, all the elements in the array are either even or oneven EXCEPT for 1 ele... |
Environment
NASM is required to build this program, and DosBox is required to run it. I'd recommend installing these using the Scoop Package Manager. Feel free to ignore install statements for any programs you have installed already.
iwr -useb get.scoop.sh | iex
scoop install git
scoop install dosbox
scoop install nas... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.