instruction
stringlengths
71
71.9k
(Here is a link to this same code on Wandbox) C++17 introduces member functions extract and insert on node-based containers (such as set and map) so that single elements can be transferred from container A to container B without any move operations. It also adds member function merge to transfer all contents of contain...
Problem: What is the largest prime factor of the number 600851475143? Hi, I'm really new with Python. Can anyone give me some feedback for this code? it seem to produce the correct answer a=600851475143 x=2 while x<(a/x): if a%x==0: a=a/x else: x+=1 print a
I have this code, but I not the best to javascript/jQuery so are there any out there who can optimize this code? $(function(){ var pos = $("header").offset().top; $(document).scroll(function(){ if($(this).scrollTop() - 10 > pos) { $('header').addClass("filled"); } else { ...
I have a grid and a class Vehicle, which will have starting point(X, Y on the grid) and direction(one of N,E,S,W) taken from user and there will be commands, L & R turns the vehicle 90 degrees around left and right respectively and M moves the vehicle one unit to faced direction. For instance, if the command is M and...
Brian Goetz provided following code of LogService with shutdown feature: public class LogService { private final BlockingQueue<String> queue; private final LoggerThread loggerThread; private final PrintWriter writer; @GuardedBy("this") private boolean isShutdown; @GuardedBy("this") private int rese...
I have the following function using in my application: applyFormSectionIdsToControls: function(formSections) { if (!formSections.length) return; var formSectionIds = []; for (var i = 0, ii = formSections.length; i < ii; i++) { formSectionIds.push(parseInt(formSections[i].id)); }; for (var...
Original Question I have updated my code based on feedback from other users and am submitting this question for re-evaluation. HTML <!doctype html> <html lang="en"> <head> <title></title> <link type="text/css" rel="stylesheet" href=styles.css /> </head> <body> <div id="player1Current...
I'm working on building a website to help people practice English. In this practice, the answer in the blank needs to be validated on hitting enter. I'd like to know if there is a simpler/better way to write it since I need to use it for a lot of pages. HTML: <p>There’s an energy here. At least, I think there is. Is it...
I been getting into javascript patterns and would love to get some feedback. I notice that I got some general helper functions. Is this a good approach of dealing with it? // carousel.js var Carousel = (function() { var timeout = 340; function init() { applyForTheseQueries(); $(window).on('resize', Helpe...
I need to create an administration board that allows devs to create or modify options and display them in a panel. The Admin needs to be the same on each call made to it. I've chosen to make all dependencies as singletons wrapped under Admin. This code only covers the approach, disconsider the lack of details. class Ad...
I'm trying to translate formulas from the 3122th sequence in OEIS database, in particular this one: B(s, m) = sum((m! / m_1! ... m_s!) * r(1)^{m_1} ... r(s)^{m_s}) where the sum is over all partitions of s such that s = m_1 + 2*m_2 + ... + s*m_s and m = m_1 + m_2 + ... + m_s. My complete solution is available at GitHu...
My code works for some smaller inputs but larger numbers causes it to hang (when running with node) // The prime factors of 13195 are 5, 7, 13 and 29. // What is the largest prime factor of the number 600851475143 ? function factorsOf(n) { var factors = []; for (var i = 1; i <= n; i++) { if (n % i === ...
? Given a list of players with their respective scores (how well does a player play soccer, from 1 to 5 points), return two teams that are as even as possible. I've created this code, which is a first version, but I really would like to hear about ideas of how can I improve it. exports.TeamCreator = (function () { ...
I'm fairly new to Angular 2 and I started off with creating a clock for my app. I tried to stick to the official documentation tutorial. Folder structure: The CSS file is still empty and the HTML is not very spectacular: <p>{{time | date:'HH:mm' }}</p> The clock component itself looks like this: import {Component} fr...
I have used linux and Windows interchangeably over the last time, and I got used to the more comfortable and options-rich syntax of linux' commands, so I decided to replicate some of them in python (with some modification) so I can use them in Windows, and started with the ls and cat commands [after adding their parent...
Here's a job shop scheduler using core.logic. I had a lot of fun coding it. I'd appreciate ideas on how to make the code faster or more readable. Setup (ns schejule.no-db (:require [clojure.core.logic :refer [== all everyg lvar run run* fresh succeed] :as l] [clojure.core.logic.fd :as fd]) (:refer-cloju...
I made this password generator I'll use in a simple Android App. I want that it generates a password using a truly random number source, but I don't have idea how to do it by now, so a let a seed parameter to generator class that will be created by that numbers source. I used the decorator pattern to compose the source...
I'm learning to do some small programs in JavaScript and I did some sort of arraySlider (I don't really know how to call it). I would like to have some feedback to improve it (more than the code itself, what I should use to make my code better in general). function arrSlider (arr,changeBy) { if(!Array.isArray(arr) ...
I wrote a function to decode GSM 7-Bit encoded messages as defined in the 3GPP standard. Example available here. I found a tool to help me check my answers here. I used the charset from here. public String decode(final byte[] data) { if (data == null) { return null; } final ByteArrayOutputStream bo...
Goal Write an R function to generate probabilities modeled by the following equation (IRT; 2 Parameter Logistic Model): Data set.seed(1) a = runif(10, 1.5, 3) b = rnorm(10, 0, 1) theta = rnorm(10000000) # the output of the implementation should result in # a matrix with 100 mil. rows and 10 columns Implementation St...
Background I am more formally trained in backend/server-side coding. Over my career I have often found myself thrown into front-end coding. I have spent the last year and a half learning JavaScript/CSS3 on an "on Demand" basis. I feel like I am getting the hang of it, doing fancier things to meet UX requirements like a...
I'm trying to write my own shared_ptr/weak_ptr implementation in C++. I have the following requirements: I do NOT need support for the following: multithreading (synchronisation) support for polymorphic types as the templated type of the shared_ptr (such as shared_ptr Base*) Reasons for wanting to write my own implem...
I'm preparing for a job as a junior/intermediate JS developer. I'm comfortable with my ability to think in higher-order functions, but less confident in my syntax and style (I have more experience in Clojure, ClojureScript). This is simple but I welcome your comments. import { Map } from 'immutable'; const coinChanger...
I try to program a stopwatch/countdown clock in FORTH with Gforth (and using Gforth-specific words). I'm a complete beginner and the following code is the basic stuff (going to add an alarm function / countdown option and more). For now the stopwatch counts from 00:00:00 (hh:mm:ss) up to 24:00:00 and pressing space p...
The following is a Python 3 script I wrote to take and delete elasticsearch snapshots. Could anyone please point out any issues? I am concerned that I have structured the code poorly (particularly the order of the functions), making it hard to read, but I am unsure how to fix that. I also made no real attempt to write ...
Write a stack class from scratch to house integers using any programming language of your choosing that implements the following methods: push(integer n) // adds the integer to top of the stack pop() // removes the top-most item from the stack peek() // gets the integer from top of the stack without...
I plan to implement a few other solvers (depth first search, A*, etc), hence why I'm using the abstract base class (which is new to me). I'm using Python 3.6, so you'll see f-string literals. I would appreciate any positive feedback (yay!) or, even more importantly, constructive (yay!) criticism. import abc from argpar...
A follow-up on this. To quote by copy/paste: Lots of languages have something that lets you build up a dynamically-sized string with minimal overhead. C doesn't, and I found myself using code that did that manually in a couple of places, so I packaged it into a class. Note that I've only implemented functionality I'm ...
I have implemented the maximum path sum of a triangle of integers (problem 18 in project euler) and I am wondering how I can improve my solution. My solution is below: def problem18(triangle, height): return dp_triangle(triangle, height, 0, 0, dict()) def dp_triangle(triangle, height, row, col, maxs): if row =...
From the requests below I've attempted to rewrite my request. I agree completely that it would be easier for our company to provide us with help desk software. Unfortunately, my department has the assignment to sit between our end users and three separate help desks that deal with different problems. We are not allowed...
The following code is working exactly as it is expected to work, the thing is that I'm sure that it can be written in a more efficient and less verbose way, any reviews? JavaScript: $(document).ready(function() { $('.hidden-content').hide(); $(".hidden-content-reveal").click(function() { var $i = $(this...
Please understand my request before commenting, I'm looking for positive critiques of my work. Anything I've done which could be done better while using the same, or similar, restrictions on data types and #include files that I've used. To put it another way, if you see anything that could be done more efficiently, usi...
I have created a python system that runs Linux core files through the crash debugger with some python extensions. This all works fine but one bit of is problematic. These files are send to the system in gzip format and consist of a single huge data file. The compressed file can often be as big as 20G. The unzipping w...
I've written a method to round a MySQL Time to two decimal places. Here's some examples: Input -> Output 13:04:27.127930 -> 13:04:27.13 00:00:14.000000 -> 00:00:14.00 02:19:03.300000 -> 02:19:03.30 07:13:00.954639 -> 07:13:00.96 My current code works, but seems a bit difficult to follow. How could I improve...
I've written the following enum and have added a function, fromValue that allows the caller to map given int into the enum value. I was wondering if the value passed to the function can be validated, or is returning a null in case the value isn't present in the map (is an invalid enum) sufficient? public enum TestEnum ...
I have a task which checks the status of a process running on a Linux server using a shell. The task should report as failed when the status is NOT RUNNING. The following works but is there a better way of checking the status string in the command. - name: check status of NC services and processes become: yes ...
I previously posted a question: Single instancing class and received some good feedback on it. I have implemented most of the changes suggested by @EBrown. I also implemented the suggestion by @t3chb0t to go with SRP. The user also suggested removing regions but these are a coding standard where I work so I can't do th...
This is basically a straightforward heap implementation. I am just moving from C to Python and I wanted to make sure that I follow Python's best practices in general. This heap is supposed to support data from any data type with any comparing function. class Heap(object): """" Attributes: heap: List rep...
A function that accepts two parameters, a parent and a child string. Determines how many times the child string - or an anagram of the of the child string - appears in the parent string. var primeMap = (function () { var map = {}; var primes = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, ...
I know it may be fairly bad. I want to find out exactly how horrendous it is and any suggestions on how to improve are appreciated. public class SudokuSolver_4{ //Creating the main sudoku board int sudokuGraph[][] = new int[9][9]; public boolean attemptAssignValue(int leftIndex, int upIndex){ //Atte...
I have written a set of test cases which cover the ansible lambda module. The entire source is available on GitHub, forked from ansible/ansible The original file is visible on github as is the module, lambda.py it tests I'd like to have a code review focusing on making the tests more reliable / less brittle making t...
A while ago, a user on Programming Puzzles and Code Golf had an idea: How about a language where all of the core commands are PPCG usernames? -- Helka Homba A list was made of username/(keyword|builtin function) pairs, but nobody really wanted to actually make the code, so it kinda went on hold. Recently (read: yes...
Working on a project that parses through an excel document to find price changes off of a webservice that is in place. The code works but is slower than expected. At first it was processing 28 products a minute, and now after some work I have it up to 80 products a minute. I've used Jetbrains dottrace to determine the...
I'm implementing rsa and aes classes in java, but i have some trouble with the rsa implementation. Since i have two keys in asymetric encryption, with two different types, i've made two differents methods, one for each. Is there a better/cleaner way to do that? private static byte[] doCrypto( int cipherMode, ...
I created a recursive, optimized, N-Queens implementation in CPP. Any suggestions for improvement? /* * Filename : queens.cpp * Author : Kevin F. * License : CopyLeft, Feb 2017 * Eight Queens : Print solutions which have N non-attacking queens placed on NxN chess board * Input : Adjust BOARD...
using System; using System.Linq; using RedditSharp; using System.Net; using RedditSharp.Things; namespace reSharp { class Program { public static void Main() { string sub = "/r/"; string saveDir = @"SAVE_DIRECTORY"; Console.WriteLine("Subreddit:"); ...
I'm trying to implement Dijkstra's algorithm to find the shortest path. This is from a challenge on CodeWars. In this scenario there is a map: [ [1,2,3], [4,8,2], [1,5,3], ] We start at the position 0, 0 and we can only move right or down. Our goal is to reach the position x, y passed to the function and get the...
I'm new to unit testing so maybe I have this all wrong, but it seems kind of useless. I want to reduce bugs and integrate some tests with a build process however I'm not seeing the benefit at the moment. How can I improve the quality of tests, like the one below? /* script */ SetAttributes = function(el, attrs) { /...
Find the maximum sum of subarray with Kadane's algorithm //test case int maxKanade, startKanade, endKanade; maxKanade = Kadane(new List<int>() { 2, -4, 6, -3, 9 }, out startKanade, out endKanade); Debug.WriteLine("{0} {1} {2}", maxKanade, startKanade, endKanade); maxKanade = Kadane(new List<int>() { 3, 4, 6, -3, -9 },...
I'd like to see if there are any suggestions on how to improve a simple conditional test at the beginning of a backup script that verifies a ZFS volume is "online" and has the name "tank". For example: % zpool list NAME SIZE ALLOC FREE EXPANDSZ FRAG CAP DEDUP HEALTH ALTROOT tank 54.5T 36.0T 18.5T ...
To Collect or Hash The VBA.Collection has a number of limitations, but it is enumerable and you can refer to items by index or key. But the VBA implementation of a Collection is 1-based, and they don't have any way of confirming membership, and the Item method returns a Variant, so they're loosely typed. Did I say Item...
I am new to C and wanted to get feedback on a small project I was working on. Coming from python, I quickly learned that a lot of things we take for granted like list class and all of its useful functions are not implemented. I wanted to see if I could make a card library to help me build multiple types of card games...
I have created a script to check for failed logins and then trawl User .bash_history for keywords. There is also processing on the .bash_history files to convert epoch to human-readable timestamps. I've run my script through shellcheck.net and the only real thing that it's complaining about are my For loops. It's sayin...
I've been messing around with SASS and BEM for the last few months. I recently starting 'thinking' in modular in terms of building out my applications (for re-usability and simplicity). I am coding my modules at the minute using the template fellow. I have tried to build this as simple as possible so that if I ever com...
What do you think about this simple implementation of B search in Java? public static boolean find(int[] arrayToScan, int valueToFind) { int startIndex = 0, endIndex = arrayToScan.length, midleIndex; while (true) { midleIndex = (startIndex + endIndex) / 2; if (arrayToScan[midleIndex] == valueToF...
First line will contain two integers N and M separated by a single space. Then the next M lines will contain three integers a, b and k separated by a single space. N is the length of the sequence. M is the number of operations performed on that sequence. a is the starting index from a sequence and b is ending index fro...
Please review my code below. I am studying the Strategy Design Pattern and I think I have implemented it correctly. Please check. I have tried to split the method definitions and the prototypes as much as possible so there are many files. Any comments are welcome. The code is copied here by a one liner in from the Linu...
I have 4 picture boxes and a collision detection to see if my mouse is on top of any of them, but I have to run the same code 4 different times, but just changing the name. Also, the else if statements can be regular if statements. PictureBox display = sender as PictureBox; Point drop = PointToClient(Cursor.Position); ...
I've created a random word generator which allows me to create random words/anagrams. Then I've created Anagram search app to find the angarams when user start typing in inbox. Could you review this with SOLID principles, Performance, Productions level ready scenarios in mind? Please be critical // Generate random wor...
I've outsourced the setup functions from my class to another file, I outsourced initDriver from the class PortalController to the class SeleniumUtility. Before: class PortalController extends Controller { protected $driver = NULL; const URL_GOOGLE = 'https://www.google.com'; const SELENIUM_SERVER_AD...
I have several lists of various objects that need to be ordered by one of their properties that contains a string representation of DateTime, whose property also varies depending on the object. The main issue with the lists is that the contained objects cannot be guaranteed to be valid DateTime representations and so s...
I ran the following code through a Leetcode.com challenge and it says the runtime for the test cases is 119ms, which puts it at the back of the pack performance wise. The goal is to remove duplicates from a sorted array of Ints and return the count of the array without dups. func removeDuplicates(_ nums: inout [Int]) -...
I am writing a class to evaluate an arithmetic expression, For now my class can convert an infix expression into postfix, it doesn't support exponents yet. public class Evaluator { public Map<String, Operator> mOperators = new HashMap<>(); public Evaluator() { addOperator(new Operator("...
I'm looking to add a thin layer of abstraction for database interaction in my application. I'm not really looking for a full blown ORM or advanced query builder. I am familiar with Diesel, but its current limitations (for my specific use case) require almost as much effort to workaround as using Rust's database adapter...
Multiple upstream servers are sending notifications to a load-balanced django app. If all the upstream servers are working correctly, the app will always receive duplicates of these notifications (since all the upstream notifiers should send the same notifications; it's just for redundancy). I want to be able to filter...
I'm using the following code to return the first index of a unique character in a large String. It works fine until I get to large strings, where it times out. Is there a faster way to accomplish the goal of getting a hold of the unique character's index using NSCountedSet? Update The string contains 25,000 characters....
Given a string of directions (example: "LLRUDDULRDRU") find the area of the rectangle defined by the lowest-left point (minx, miny) and the highest-right point (maxx, maxy) the robot was in. The canonical solution I think would be. int area(char* directions) { char * c = directions; int x=0, y=0, minx=0, max...
I'm delving into JavaScript, and ES6, but want to be able to pass additional options to functions after a spread object. Coming from Python, you'd just use keyword arguments, such as def sum(*args, fn=add), where in JavaScript you'd either need the optional argument before the required arguments, or to handle it in the...
I would like to get a deeply-nested value, for example {"a":{"b":{"c":"myValue"}} by providing the keys to traverse. I tried chaining together .get() but that didn't work for cases where some of the keys were missing—in those cases, I want to get None instead. Could this solution be improved? #!/usr/bin/env python # en...
I don't work much in Word VBA so I approached this similar to how I'd approach it in excel, which may not have been optimal. I also didn't see any places for errors to be handled. This takes a Word document that has a list of URLs (pointing to .jpg), takes the URLs, places them as images on another sheet and then scale...
Is there a simple way to concatenate all of the fprintf(qFile, "%-1.1c", mod[cnt].name[x]); expressions into a small number of expressions? Appreciate any other suggestions. #include "stdafx.h" #include <stdio.h> #include <iostream> // fprintfQuestion.cpp : Defines the entry point for the console appli...
Background I have process tons of DataFrames with shapes of ~230 columns x ~2000-50000+ rows. Here is an extremely simplified example; numbers colors 0 0.03620894806802 1xYellow ; 2xRed 1 0.7641262315308163 2xYellow ; 1xOrange 2 0.5607449770945651 3xYellow ; 2xGreen 3 0.6714547913365702 ...
Introduction/Disclaimer This is a project for educational purposes. I'm not intending to replace the "award-winning" Collections Framework in java.util. I'm just looking for constructive criticism. For obvious reasons, I'm tagging it as reinventing-the-wheel. I'd like to see someone break my code. Preferably in a multi...
This will be my last submission of this project for review as it's being submitted this evening. I have updated my code based on feedback from other users. I would appreciate any and all feedback from the community. Thanks in advance. Original submission Follow Up HTML <!doctype html> <html> <head> <titl...
The code implements fully generic sliding window with linear complexity. It should usually be paired with transforming iterator to reach full potential. Sliding window is a grouping of elements by exactly length of sliding window, then "sliding" the window by one element on each iteration. Example: Given A = [0, 1, 2,...
The question is follow-up to preprocessing iterator. Specification: Given Functor functor (which is Callable) and Iterator iterator (which is OutputIterator), iterator is created that behaves the same as underlying iterator, except it applies a functor to the incoming data and then passes the result into underlying it...
I was wondering if this FloodFill algorithm was correct for this game I am trying to create it is in the selectColor method of my GameController.java class: import java.awt.*; public class GameController /*implements ActionListener*/ { private GameModel model; private MyStack dots; private int size; /** * Construct...
I am making changes to a Python script that converts MySQL scripts to PostgreSQL, and I want to replace strings such as id INTEGER NOT NULL AUTO_INCREMENT with id SERIAL NOT NULL. This is the code I got to work: import re line = 'id INTEGER(11) NOT NULL AUTO_INCREMENT,' numeric_types = ['(BIG|MEDIUM|SMALL|TINY)*INT(E...
I wrote a word-search solver in Python3. It takes input from a file named input.txt and takes the word as a command-line argument. It is intended to be run as a script, so I didn't really bother with code reusability / extendability. It assumes that input.txt contains the word search file looking something like this: a...
Problem statement You have a pile of n stones that you want to split into multiple piles, as well as a set, S, of m distinct integers. We define a move as follows: First, choose a pile of stones. Let's say that the chosen pile contains y stones. Next, look for some x in S such that x<>y and y is divisible by x (i.e...
I am a self-taught coder, and have been learning Java for the last 2 months. I have recently created a snake game in Java with the help of an online tutorial. I have rearranged the program into separate classes & methods. I am skeptical on how good of a programmer I am, and I code messy. I don't really want help on how...
I did this spider that checks the stock of references list (around 3500 references). Now the spider takes around 37 seconds to scrape 400 references. The CPU is around 5%, the network card (1Gbps) around 18%. My internet connection is 300Mbps symmetric and it's only connected to this computer. Any idea to improve perfo...
I need to generate an array of int values for a given size, the values should be random and unique. the following implementation is "ok" for small values [1,10k], I would like to get some feedback on better implementation /** * Generate an array of random & unique values in the interval [0,desiredSize*3] * To use onl...
I'm currently working on an API that behaves incredibly unpredictable at runtime. Context: We run the same call 100 times without delay in between. A call can take anywhere from ~200 ms to ~5 seconds. Usually it 'builds up' gradually and drops down quickly after about half a minute. This problem only occurs on a select...
I'm currently coding something where I have Objects that take on an ID, and are stored in a List. For easy retrieval, the ID of the object is it's index in the list. However, that means that the object cannot be removed from the list without everything going to hell, since the list will be re-indexed and thus I won't b...
I have a C# Service that takes a filter string and a FilterMap class and generates an Expression<Func<T, bool>> for use within Linq to * Scenarios (currently it is in use to create dynamic filtering for documentdb queries). Filters have the form *parameter*_*operation*_*value*, for example: firstName_eq_Joe. Multiple f...
I have elements that are generated dynamically on the screen. I have bars and diamonds. The problem is I have hundreds of different types of bars or diamonds that need to be rendered on the screen. The bars and diamonds are tasks and milestones on a gantt chart. There are hundreds of different types and each type has...
Task: calculate average price for each stock, using input data, which consists of stock id (int) and its price (float). It's important to detect jumps in prices, therefore need to keep correct sequence of input data, i.e. prices for the same stock id should be processed in correct sequence (from top to bottom). Stock i...
I know that other people already did the same already, but I'm learning C++ (C++11/14) coming from C (I'm reading Programming: Principles and Practice Using C++, by Bjarne Stroustrup), and this is my OOP implementation of a matrix (N by M size). At the moment it doesn't use template for generic types and uses double, a...
As much as I hate it, sometimes providing passwords to people has to be done electronically. When I do that I try to remove any ambiguity that might be created by the font, user etc. and provide a phonetic translation of the string. For things like 0 and O or l and I which might not be obvious at first. The function b...
Just started learning C. I hope my code adheres to best practices and idioms #include <stdio.h> #include <ctype.h> #include <time.h> #include <stdlib.h> int main(void) { int iRandomNum; int iGuess; srand(time(NULL)); iRandomNum = (rand() % 10); printf("Guess a number between 1 and 10:"); scanf("%d", &iGuess); // isdi...
Recently I wanted to teach the AI of my castle game how to use the spells that I have added to the game. You can try out the game here: Castleparts Initially I thought that I would have to add subclasses for each of the four playable races in order to account for the different spells that each one has available. Howev...
I am not sure if I am right by asking this here, but I have got a big site, but I feel like the code is very messy. I am using plain CSS to get things done. I don't want to add frameworks and stuff like that. I want to get this code more tidy without duplications, while still be readable. * { margin: 0; paddi...
I'm currently using this method to test a string if it valid JSON. The JToken class depends on Newtonsoft.Json.Linq. public static bool IsValidJson(this string stringValue) { bool returnValue = false; string value = null; if (!String.IsNullOrEmpty(stringValue)) value = stringValue.Trim(); if...
I am a self taught VBA user. I was asked to look at the code from a tool which has stopped working due to a data overflow and "fix" it. I was told the code was 'optimised' so that it took only 2 hours to run instead of four. They did this by remove loops. I didn't have an issue with my 64-bit Excel, but another user s...
The text file is laid out like this: first name, last name, wins, losses dex,kop,5,6 desder,jok,0,11 aslan,vert,11,0 jax,sas,2,9 buy,guy,1,10 Code: def points(): template = "|{0:<30}|{1:<30}|{2:<30}|{3:<30}|{4:<30}" lol = template.format("1st name: ","2nd Name: ", "won: ", "lost: ","points: ") print(...
I am a beginner coder learning Python. This is a simple exercise from the thinkpython book. I would like to know if this circular referencing to restart the program the best way to do it. Also if you have other comments as to how to improve the code, please feel free to suggest. def program_restart(): print("Would ...
For fun I wanted to create a lock implementation that was about as fast as one using futexes but that used used pipes instead and that queues waiters in user space instead of in-kernel. For the queue the code uses an optimized version of the lock-free algorithm from Simple, Fast, and Practical Non-Blocking and Blocking...
I'm using the following as a wrapper for the HtptClient because it doesn't implement an interface -- which makes mocking more difficult. This logic also supports invalid and self-signed certs. public class HttpClientWrapper : IHttpClient { private readonly HttpClient _client; public Uri BaseAddress { ...
Original post here. I've taken @ThomasWard's advice, and also added a couple other things. #!/usr/bin/env python import tokenize import sys import json def handle_token(type_, token, (srow, scol), (erow, ecol), line): # Return the info about the tokens, if it's a NAME token then replace it if tokenize.tok_n...